Kotlin Getters And Setter + LateInit

 


Kotlin Getters & Setters With Example

  • If you want to execute some logic before setting or getting the property of an object, you can use getters and setters. 
  • You can consider these as functions that are executed when you either get the property or set the property of an object.
  • But why we want to do this? Why we want to execute code before accessing it? Let's understand this with an example - 
fun main() {
    val user = User("John", 20, "abc@cheezycode.com")
    user.age = -10
}

class User(nameParam: String, ageParam: Int, emailParam: String)
{
    var name : String = nameParam
    var age: Int = ageParam
    var email: String = emailParam
}
  
Explanation - 
  • Here we have defined a User class - inside the main function, we are setting the value of age to a negative value. 
  • In a real-world scenario, you don't want any user to have negative age. So you also want to prevent this in your code. You don't want anybody to set a negative value to age property accidentally.
  • To prevent this, you can create a setter - that gets called when you set the property. You can write the logic inside the setter to prevent this from happening. Let's see how to define a setter for age property - 

class User(nameParam: String, ageParam: Int, emailParam: String)
{
    var name : String = nameParam
    var age: Int = ageParam
    set(value) {
        if(value < 0)
        {
            println("Age can't be negative")
        }
        else
        {
            field = value
        }
    }
    var email: String = emailParam
}
    
Explanation - 
  • In the above code, we have created a setter on the age property. We have written custom code to prevent the value from being negative. 
  • Value inside the set(value) is just a variable name, you can name it whatever you want. This will hold the value which is assigned to the property. 
  • Inside the setter, we have added an if-else condition to check if the value assigned is negative or not. If the value is negative then "Age can't be negative" will be printed.
  • In the else case, we have set the value to a field (a special variable that points to the property). This field is also known as the backing field. This backing field is used inside the setter to set the value to that property. (field = value)

Kotlin Getters With Examples

  • Just like setters, we can also define getters. While accessing the property, the code inside the getter is executed. 
  • These getter functions are used to format any property value while accessing the value. Let's see this in action  - 

fun main() {
    val user = User("John", 20, "ABC@CheezyCode.com")
    println(user.email)
}

class User(nameParam: String, ageParam: Int, emailParam: String)
{
    var name : String = nameParam
    var age: Int = ageParam    
    var email: String = emailParam
    get(){
        return field.toLowerCase()
    }
}
    

Explanation - 

  • In the above code snippet, we have defined a getter function - that is executed when you access email property. 
  • Emails are generally in lowercase, whatever the user has entered - you will always format it as a lowercase string. 
  • To do this, we have defined a getter that will return the email property in lowercase format. In the main function, we have passed email as ABC@CheezyCode.com - line after this where we have accessed user.email will print abc@cheezycode.com

Simple syntax for Getter & Setter - 

var <propertyname>[: <propertytype>] [= <property_initializer>]
    [<getter>]
    [<setter>]
    

LateInit In Kotlin With Example

  • When you want to initialize the value to a property later in the program, you mark the property as lateinit. LateInit means late initialization.
  • While setting up the constructor if you don't know the value to be assigned - you use lateinit.
  • Lateinit property is declared as var because we have to assign it a value later in the program. We cannot define these properties as primitive types such as Int, Byte, Long, etc.
  • If you try to access a lateinit variable before assigning it a value, you will get kotlin.UninitializedPropertyAccessException.

fun main() {
    val user = User()
    user.setValue("John")
    println(user.name)
}

class User
{
    lateinit var name:String
    fun setValue(nameParam: String){
        name = nameParam
    }
}
      

That's it for this article. For more articles on Kotlin Tutorials For Beginner Series - refer to this.

Happy Learning !! Cheers From CheezyCode.


Comments

Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Android Apps - Getting Started