Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override interface property with constructor parameter with different name

Tags:

kotlin

I have this code:

class AnyUsernamePersistentNodePath(override val value: String) : AnyPersistenceNodePath {
    override val key = "username"    
}

and

interface AnyPersistenceNodePath {
    val key: String
    val value: String
}

So far, so good. Now I want parameter value in the constructor to be named username, instead of value. But, obviously, keep overriding interface's property value. Is that possible in Kotlin?

I know that I can do:

class AnyUsernamePersistentNodePath(val username: String) : AnyPersistenceNodePath {
    override val key = "username"
    override val value = username
}

but I'd like to avoid it.

like image 580
Héctor Avatar asked Oct 11 '16 17:10

Héctor


1 Answers

You can do what you want simply by removing val from the constructor parameter, so that it is a parameter and not a member. Your final class would be:

class AnyUsernamePersistentNodePath(username: String) : AnyPersistenceNodePath {
    override val key = "username"
    override val value = username
}

You cannot otherwise change the name of something that you are truly overriding. But you can pass in the value to be assigned to a member later during construction, as my slightly modified version of your code shows.

like image 70
2 revs Avatar answered Dec 28 '22 14:12

2 revs