Anyone know why i would want to use a property extension as opposed to just defining a local class extension? here is an example of a property extension that i have tried:
class MyClass {
val String.concatMyName: String
get() {
return plus("FRED")
}
}
the usage can be “my name is:“.concatMyName but i could also do
class MyClass{
fun String.concatMyName2() = this.plus("FRED")
}
usage would be: “my name is:“.concatMyName2() so i'm not seeing the value yet.
i thought possibly one value is that its utilizing the getter so its not having to put the static code in memory. would that be the savings only ?
The two are very similar, but there are some subtle differences:
As you show, calling the extension getter doesn't need parens (round brackets), but calling the extension method does.
Down at the bytecode level, the extension getter has a method name beginning with get
, which would matter if you were calling it from Java or another JVM language.
The two versions imply different things to whoever's reading the code. Conceptually, a getter returns part of the object's state, so is usually consistent (returning the same value while the object's state doesn't change), free of visible side effects, very unlikely to throw an exception, and quick (e.g. without making network calls or long calculations); it's also usually consistent with calls to a corresponding setter. There's nothing stopping you from writing a getter which doesn't conform to those, but then it wouldn't fit the mental model of a getter and so would be likely to cause confusion/bugs. Whereas if it does fit, then it would probably be clearer as a getter.