Kotlin是否具有扩展类来像Swift一样进行接口 [英] Does Kotlin has extension class to interface like Swift

查看:79
本文介绍了Kotlin是否具有扩展类来像Swift一样进行接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我们可以使用如下所示的接口扩展类

In Swift, we could extend a class with an interface as below

extension MyExtend {
   public var type: String { return "" }
}

extension MyOrigin: MyExtend {
   public var type: ListItemDataType {
       return "Origin"
   }
}

我们在Kotlin中具有这种能力吗? (例如,扩展接口)

Do we have that capability in Kotlin? (e.g. extend an interface)

推荐答案

是的,科特林确实具有 Extensions —与 Swift 类似.

Yes, Kotlin does have Extensions — similar to 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)

科特林:

class C {
    fun foo(i: String) { println("class") }
}

fun C.foo(i: Int) { println("extension") }

C().foo("A")
C().foo(1)

输出:

class
extension

您需要阅读一些关键差异.

There are some key differences you'll want to read up on.

扩展实际上并不修改它们扩展的类.通过定义 扩展,您无需将新成员插入类,而只需 可以在此变量上使用点符号调用的新函数 类型.

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

这篇关于Kotlin是否具有扩展类来像Swift一样进行接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆