Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional interface in Kotlin

In Swift, we can define a protocol that can be conformed by a class or struct based on condition:

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)
  }

}

The AlertPresentable protocol is restricted and can only be conformed by an UIViewController. Is there a way to achieve the same result in Kotlin?

like image 859
Benjamin Avatar asked Jan 03 '23 16:01

Benjamin


1 Answers

If I understand correctly what you're trying to accomplish, you can use an extension function with multiple types as upper bounds of the receiver type:

fun <T> T.presentAlert(message: String) 
    where T : UIViewController, T : AlertPresentable {
    // ...
}  
like image 109
yole Avatar answered Jan 05 '23 16:01

yole