Please use the following format for the title of this thread (then simply delete/replace this text with the content for the thread):
Title: Programming Kotlin: misleading example (229)
There is a section entitled Don’t Change Behavior of Existing Methods
, which warns against using extension functions to swizzle or change the behavior of existing functions. The example implies that extensions can be used to shadow or override those which already exist on a class. The example goes on to eventually mention that this example overrides the extension provided by the Kotlin standard library, but I think this example and the way it’s phrased could lead junior developers or those new to Kotlin to think that you can override or hijack a function defined on a class through extension functions, which you cannot. It’s not possible.
For example:
val String.length get() = 8
@Test
fun testBogus() {
val foo: String = ""
assertEquals(0, foo.length)
}
// will always yield 0, because the property/function on String.kt will always be called instead.
My opinion is that this example, should at least point out this fact.