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?
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 {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With