Setters and getters (again)


#1

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

I’m implementing this Interface; https://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/provider/ClientDetails.html

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.


#2

http://kotlinlang.org/docs/reference/properties.html#backing-properties


#3

You mean something like this?

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

?


#4

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


#5

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

client.setClientId("new_id").invoke()

#6

Thanks!


#7

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.


#8

Yes it can be