Professional Documents
Culture Documents
TRN Setr
TRN Setr
Content
In Kotlin, setter is used to set the value of any variable and getter is used
to get the value. Getters and Setters are auto-generated in the code. Let's
dene a property 'name', in a class, 'Company'. The data type of 'name' is
String and we shall initialize it with some default value.
class Company {
var name: String = ""
get() = field // getter
set(value) { // setter
field = value
}
}
fun main(args: Array<String>) {
val c = Company()
c.name = "GIET University" // access setter
println(c.name) // access getter
}
Continue....
class Registration( email: String, pwd: String, age: Int , gender: Char) {
var email_id: String = email
// Custom Getter
get() {
return field.toLowerCase()
}
var password: String = pwd
// Custom Setter
set(value){
field = if(value.length > 6) value else throw
,→ IllegalArgumentException("Passwords is too small")
}
var age: Int = age
// Custom Setter
set(value) {
field = if(value > 18 ) value else throw
,→ IllegalArgumentException("Age must be 18+")}
Continue....