Properties, Getters and Interfaces


#1

Probably asked several times here already, searching didn’t return a direct answer, so please forgive me asking.

While writing a blog post about delegation in Kotlin [1] I tried to create an interface with a getter.

interface HasName {
fun getName():String
}

class Person(val name:String)

This does not work. I wanted to confirm that this is not possible, or where I’m doing something wrong. How would I implement this?

class Person(val n:String) {
fun getName():String = n
}

or

class Person(n:String) {
val name = n
}

[1] http://codemonkeyism.com/exploring-delegation-in-kotlin/


#2

You have to declare the interface.

interface HasName {
    val name: String
}

class Person(_name: String) : HasName {
    override val name = _name
}

Data classes are even more concise:

data class Person(override val name: String) : HasName

#3

Thanks! Do dataclasses support class delegation?


#4

Yes, data classes do support delegation. However it doesn’t make much sense to use a data class as the class which delegates to another class, whereas data class could be used as a delegation target.

// data class is ok here
data class NameHolder(override val name: String) : HasName

// shouldn't be a data class!
class Person(named : HasName) : HasName by named

val named = NameHolder("Amy")
val person = Person(named)
println(person.name) // Amy

#5

Ok, thanks


#6

This concise syntax works with non-data classes as well.