How to use get() with backing fields in kotlin

253 Views Asked by At

in the below code I am trying to create a getter method as a backing field. so that, when the getLastNameLen property is invoked it should return the length of the lastNameset.

please refer to the code below and help me to fix the bug.

how to display output of the backing fields

code:

class Thomas (val nickname: String?, val age : Int?) {

    //backing field 1
    var lastName : String? = null
        set(value) {
            if (value?.length == 0) throw IllegalArgumentException("negative values are not allowed")
            field = value
            println("lastname backing field set: ${field} ")
        }

    val getLastNameLen
        get() = {
            this.lastName?.length
        }
}

output

lastname backing field set: jr.stephan 
lastName is jr.stephan
lastNameLen is () -> kotlin.Int?
1

There are 1 best solutions below

0
On

This is because you are using the = operator which is setting the getter to be a lambda.

You have two options:

val getLastNameLen
    get() {
        return this.lastName?.length
    }

OR

val getLastNameLen
    get() = this.lastName?.length

basically use the brackets right after get() to make a getter function, or if you can do it in one line use an = right after the get() but don't include the {} otherwise it will treat it like its a lambda