How are extensions resolved in Kotlin and what doest it mean?
How are extensions resolved in Kotlin and what doest it mean?
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:
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:
class Example {
fun foo() { println("Member") }
}
fun Example.fo...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào