有没有办法在 Kotlin 中完成 Swift 的协议组合

Is there a way to do Swift's Protocol Composition in Kotlin

因此,对于 Swift,我们可以使用 & 运算符创建新类型或将其作为参数传递给方法。

示例Swift代码:

protocol Fooable {}
protocol Barable {}

// the new protocol
typealias FooBarable = Fooable & Barable

// method parameter 
func doSomethingFor(object: Fooable & Barable) { ... }

有没有办法在 Kotlin 的接口中执行此操作?

从函数方面,您可以使用 where-clause:

的通用函数来处理它
fun <T> foo(obj: T) where T: Fooable, T: Barable {
    ...
}

请检查以下代码:

interface A{

}

interface B{

}

fun <T> check(variable: T) where T : A, T: B{
    print("Hello");
}

如果你试图传递一个没有向他们双方确认的变量,上面的代码会给你编译时错误