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

What is basic difference between fold and reduce in Kotlin? When to use which?

middle

What is the idiomatic way to deal with null able values, referencing or converting them?

middle

What are some disadvantages of Kotlin?

Bình luận

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

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