Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

kotlin property extensions vs local class extensions, which is better?

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 ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...