Kotlin是否支持或将来制定类似于Swift中协议组成的接口组成计划? [英] Does Kotlin support or have future plan for Interface Composition similar to Protocol Composition in Swift?
问题描述
到目前为止,我找到的答案可能是否",但我想知道将来是否有任何计划支持此功能.这就是Swift中的样子.
The answer I found so far is probably a NO but I wonder if there is any plan of future support for this feature. Here is what it looks like in Swift.
协议组合物的形式为SomeProtocol&另一个协议.您可以根据需要列出任意数量的协议,并用与号(&)分隔.除了协议列表以外,协议组成还可以包含一个类类型,您可以使用它来指定所需的超类.
Protocol compositions have the form SomeProtocol & AnotherProtocol. You can list as many protocols as you need, separating them with ampersands (&). In addition to its list of protocols, a protocol composition can also contain one class type, which you can use to specify a required superclass.
protocol Named
{
var name: String { get }
}
protocol Aged
{
var age: Int { get }
}
func wishHappyBirthday(to celebrator: Named & Aged)
{
print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}
推荐答案
您无法在Kotlin中显式定义交集类型,但可以使用泛型类型约束在函数参数中实现交集类型.像这样:
You can not explicitly define intersection types in Kotlin, but you can use generic type constraints to achieve it in a function parameter. Like this:
interface Named {
val name: String
}
interface Aged {
val age: Int
}
fun <T> wishHappyBirthday(celebrator: T) where T : Named, T : Aged {
println("Happy birthday, ${celebrator.name}, you're ${celebrator.age}!")
}
这篇关于Kotlin是否支持或将来制定类似于Swift中协议组成的接口组成计划?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!