Categories: java, android, swift, kotlin

Can you scope a Kotlin interface for use with only certain classes?

1 answer

I come from primarily an iOS background. In Swift, we can make Protocols which are designed to be implemented by specific classes:

protocol MyViewControllerProtocol where Self: UIViewController {     func doViewControllerThings() } 

This is super powerful because it allows us to extend the protocol with a default implementation and use methods on self

extension MyViewControllerProtocol {     func doViewControllerThings() {         self.view.addSubview(UIView())     } } 

I am trying to do something similar in Kotlin for an Android project. Is this possible?

Received answer to this question:
The best answer according to the author of the question:

Not strictly. You could add a generic property that is intended for the implementer to return itself, but the compiler won't prevent you from providing some other object to satisfy the property.

interface SomeInterface {     val thisRef: Activity      // ...  } 

The above interface can call functions on thisRef in its default function implementations.

An implementing class must provide the value for thisRef:

class MyActivity: Activity(), SomeInterface {     override val thisRef = this      //... }