https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

jeggy

02/22/2024, 11:42 AM
Hi I'm wondering if I have reached a limitation, bug or just a misunderstation of Kotlin. I'm trying to overwrite a function that is being used by another function implemented by a delegated implementation, like shown below:
Copy code
interface Run {
    fun printA()
    fun printWith(value: String)
}

val DefaultRun = object: Run {
    override fun printA() = printWith("value")
    override fun printWith(value: String) = println("Hello with: $value")
}

class Custom: Run by DefaultRun {
    override fun printWith(value: String) = println("Goodnight with: $value")
}

fun main() {
    // Prints "Hello with: value"
    // But I expected it to print "Goodnight with: value"
    Custom().printA() 
}
y

Youssef Shoaib [MOD]

02/22/2024, 11:54 AM
That's an interesting place where using an extension function changes behaviour a lot:
Copy code
interface Run {
    fun printWith(value: String)
}

fun Run.printA() = printWith("value")

val DefaultRun = object: Run {
    override fun printWith(value: String) = println("Hello with: $value")
}

class Custom: Run by DefaultRun {
    override fun printWith(value: String) = println("Goodnight with: $value")
}

fun main() {
    // Prints "Goodnight with: value"
    Custom().printA() 
}
🙌 1
j

jeggy

02/22/2024, 11:59 AM
good idea. Will just go with this route 👌