在 Swift 中,我们可以使用如下接口(interface)扩展一个类
extension MyExtend {
public var type: String { return "" }
}
extension MyOrigin: MyExtend {
public var type: ListItemDataType {
return "Origin"
}
}
我们在 Kotlin 中有这种能力吗? (例如扩展接口(interface))
最佳答案
是的,Kotlin 确实有 Extensions
— 类似于 Swift。
swift :
class C {
func foo(i: String) { print("class") }
}
extension C {
func foo(i: Int) { print("extension") }
}
C().foo(i: "A")
C().foo(i: 1)
Kotlin :
class C {
fun foo(i: String) { println("class") }
}
fun C.foo(i: Int) { println("extension") }
C().foo("A")
C().foo(1)
输出:
class
extension
您需要了解一些关键差异。
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
We would like to emphasize that extension functions are dispatched statically, i.e. they are not virtual by receiver type. This means that the extension function being called is determined by the type of the expression on which the function is invoked, not by the type of the result of evaluating that expression at runtime.
关于swift - Kotlin 是否有像 Swift 那样的接口(interface)扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50362347/