Schidu Luca
Schidu Luca

Reputation: 3947

Implementing properties declared in interfaces in Kotlin

I'm new to Kotlin, so I have this interface.

interface User {
    var nickName : String
}

Now I want to create a class PrivateUser that implements this interface. I have also to implement the abstract member nickName.

Via constructor it's very simple

class PrivateUser(override var nickName: String) : User

However when I try to implement member inside the class Idea generates me this code

class Button: User {

override var nickName: String
    get() = TODO("not implemented")
    set(value) {}
}

It's confusing to me how to implement it further.

Upvotes: 11

Views: 32101

Answers (1)

Ruckus T-Boom
Ruckus T-Boom

Reputation: 4786

Properties must be initialized in Kotlin. When you declare the property in the constructor, it gets initialized with whatever you pass in. If you declare it in the body, you need to define it yourself, either with a default value, or parsed from other properties.

Some examples:

class Button : User {
    override var nickname = "Fred"
}

class Button(val firstName: String, val lastName: String) : User {
    override var nickname = "${firstname[0]}$lastname"
}

The code generated by IDEA is useful if you want a non-default getter and/or setter, or if you want a property without a backing field (it's getter and setter calculate on the fly when accessed).

More examples:

class Button : User {
    override var nickname = "Fred"
        get() = if (field.isEmpty()) "N/A" else field
        set(value) {
            // No Tommy
            field = if (value == "Tommy") "" else value
        }
}

class Button(val number: Int) : User {
    var id = "$number"
        private set
    override var nickname: String
        get() {
            val parts = id.split('-')
            return if (parts.size > 1) parts[0] else ""
        }
        set(value) {
            field = if (value.isEmpty()) "$number" else "$value-$number"
        }
}

Upvotes: 18

Related Questions