【问题标题】:Is there a way to do Swift's Protocol Composition in Kotlin有没有办法在 Kotlin 中做 Swift 的协议组合
【发布时间】:2019-06-25 09:47:48
【问题描述】:

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

示例 Swift 代码:

protocol Fooable {}
protocol Barable {}

// the new protocol
typealias FooBarable = Fooable & Barable

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

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

【问题讨论】:

    标签: swift kotlin interface protocols swift-protocols


    【解决方案1】:

    请检查以下代码:

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

    如果您尝试传递一个不确认给他们俩的变量,上面会给您编译时错误

    【讨论】:

      【解决方案2】:

      从函数方面,您可以使用where-clause 使用通用函数来处理它:

      fun <T> foo(obj: T) where T: Fooable, T: Barable {
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        相关资源
        最近更新 更多