有没有办法在 Kotlin 中进行 Swift 的协议组合

Zon*_*ame 4 protocols interface kotlin swift swift-protocols

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

示例 Swift 代码:

protocol Fooable {}
protocol Barable {}

// the new protocol
typealias FooBarable = Fooable & Barable

// method parameter 
func doSomethingFor(object: Fooable & Barable) { ... }
Run Code Online (Sandbox Code Playgroud)

有没有办法在 Kotlin 的接口中做到这一点?

Sah*_*nda 5

请检查以下代码:

interface A{

}

interface B{

}

fun <T> check(variable: T) where T : A, T: B{
    print("Hello");
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试传递一个未向双方确认的变量,则上述内容会给您带来编译时错误