If you implement a Java interface that defines a g...
# getting-started
r
If you implement a Java interface that defines a getter:
Copy code
interface Something {
  String getAConstant();
}
and you want the value of
getAConstant
to be a constant, is there a less verbose way than this?
Copy code
class ConcreteSomething : Something {
  private val _constant = "constant value"
  override fun getAConstant(): String = _constant
}
(It's not actually a String, it's calculated by calling other methods on a supertype using a constructor value, just simplifying things.)
k
Copy code
override fun getAConstant() = "constant_value"
(It can thereafter be used as though it were a val,
ConcreteSomething().aConstant
, but it has to be defined as a function because it's a Java interface.)
j
@Klitos Kyriacou The initializer in the example is a constant string but it's mentioned that in real life the expression is more complex. I think what Rob meant is that the value shouldn't be recomputed every time. If you define the function this way, the body will be re-evaluated every time, which I think is not what Rob wants.
👍 3
s
j
Ah thanks, I was looking for that link!
r
Thanks, yes that was what I was getting at, good to know I haven't missed some better way.
j
So yeah I think your best option right now is what you already did: define a private property with initializer, and then just read that property in the explicitly overridden getter function.
👍 1