Kotlin 中的条件接口
Conditional interface in Kotlin
在Swift中,我们可以根据条件定义一个可以被class
或struct
遵守的协议:
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)
}
}
AlertPresentable
协议受到限制,只能由 UIViewController
遵守。有没有办法在 Kotlin 中实现相同的结果?
如果我正确理解了您要完成的任务,您可以使用具有多种类型的扩展函数作为接收者类型的上限:
fun <T> T.presentAlert(message: String)
where T : UIViewController, T : AlertPresentable {
// ...
}
在Swift中,我们可以根据条件定义一个可以被class
或struct
遵守的协议:
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)
}
}
AlertPresentable
协议受到限制,只能由 UIViewController
遵守。有没有办法在 Kotlin 中实现相同的结果?
如果我正确理解了您要完成的任务,您可以使用具有多种类型的扩展函数作为接收者类型的上限:
fun <T> T.presentAlert(message: String)
where T : UIViewController, T : AlertPresentable {
// ...
}