Kotlin中的条件接口

Ben*_*min 4 interface kotlin swift swift-protocols

在Swift中,我们可以定义一个可以由a classstruct基于条件符合的协议:

protocol AlertPresentable {
   func presentAlert(message: String)
}

extension AlertPresentable where Self : UIViewController {

 func presentAlert(message: String) {
    let alert = UIAlertController(title: “Alert”, message: message,  preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: “OK”, style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
  }

}
Run Code Online (Sandbox Code Playgroud)

AlertPresentable协议受到限制,只能通过一致UIViewController.有没有办法在Kotlin中获得相同的结果?

yol*_*ole 9

如果我正确理解了您要完成的任务,您可以使用多种类型的扩展函数作为接收器类型的上限:

fun <T> T.presentAlert(message: String) 
    where T : UIViewController, T : AlertPresentable {
    // ...
}  
Run Code Online (Sandbox Code Playgroud)