Kevin_TA
Kevin_TA

Reputation: 4675

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

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?

Upvotes: 2

Views: 969

Answers (2)

squirrel
squirrel

Reputation: 5488

I don't think you can restrict interfaces in this way, but you can restrict functions:

interface MyViewController

fun <T> T.doViewControllerThings() where T : UIViewController, T : MyViewController {
    view.addSubview(UIView())
}

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93649

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

    //...
}

Upvotes: 1

Related Questions