Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing properties declared in interfaces in Kotlin

Tags:

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.

like image 715
Schidu Luca Avatar asked Aug 25 '17 13:08

Schidu Luca


1 Answers

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"
        }
}
like image 111
Ruckus T-Boom Avatar answered Oct 10 '22 10:10

Ruckus T-Boom