Setters and getters (again)


I know this has been asked a lot, but I can’t wrap my head around it.

I’m implementing this Interface;

when I implement it like this :

 private var clientId = ""
 override fun getClientId() = clientId

… then the interface is satisfied but I can’t do

client.clientId = clientId // Err: Val cannot be reassigned

I tried the various options along but am getting syntax errors along the way.

What the way to do this? I want to create a ClientDetail in a Service.



You mean something like this?

private var _clientId = ""
fun setClientId(clientId: String) = { this._clientId = clientId } 
override fun getClientId() = _clientId



Yes, if you requires a public setter (that returns a lambda function)


In other words if you want your setter to work like this:





I’m not sure if the Kotlin/Java interop supports this, but what I normally do in pure Kotlin in this case is:

override var clientId = ""
    private set

This works even if the interface or superclass defines a val rather than a var, but I’m not sure if a Java setter in an interface or superclass class can be overridden in this way.


Yes it can be