swift - Kotlin 是否有像 Swift 那样的接口(interface)扩展类

标签 swift kotlin

在 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.

https://kotlinlang.org/docs/reference/extensions.html

关于swift - Kotlin 是否有像 Swift 那样的接口(interface)扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50362347/

相关文章:

java - 如何在 jackson 中编写自定义属性反序列化器

kotlin - 如何使用不变变换在Kotlin中反转 map

android - 统一自动调整多个 TextView 的大小

kotlin - 传递 null 时,有没有办法在非可选参数上使用默认值?

android - 是否可以将实时过滤器应用于android-camerax?

ios - 如何从 appDelegate 到 viewController

arrays - Swift 3 中数组平衡点的公共(public)函数

ios - 如何使用swift在IOS中实现跑马灯标签

swift - CoreLocation 的问题

swift - Swift 字节中的 UDP 消息已读但无消息