Câu hỏi phỏng vấn Kotlin
Câu hỏi

How are extensions resolved in Kotlin and what doest it mean?

Câu trả lời

Extensions in Kotlin are resolved statically, which means that the extension function to be called is determined at compile time based on the declared type of the variable, not its runtime type[1][2].

For example, if you have:

kotlin Copy
open class Shape
class Rectangle : Shape()

fun Shape.getName() = "Shape"
fun Rectangle.getName() = "Rectangle"

fun printClassName(s: Shape) {
    println(s.getName())
}

And call printClassName(Rectangle()), it will print "Shape", because the extension function called depends only on the declared type of the parameter s, which is Shape[1].

If a class has a member function, and an extension function is defined which has the same receiver type, the same name, and is applicable to given arguments, the member always wins[2]. For example:

kotlin Copy
class Example {
    fun foo() { println("Member") }
}

fun Example.fo...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

Where should I use var and where val ?

junior

How to initialize an array in Kotlin with values?

middle

Explain the null safety in Kotlin

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào