In Kotlin's interfaces with default implementation...
# announcements
i
In Kotlin's interfaces with default implementations, there's no way to constrain the interface to a specific implementation / access it, right? Edit: Here's a snippet in Swift of what I mean. I'm almost sure it's not possible in Kotlin, but just want to confirm (and see what alternative can be used)
Copy code
protocol ChildViewController where Self: UIViewController { // <--ChildViewController is "interface" and it's constrained to a specific class

    func foo()
}

extension ChildViewController {

    func foo() { <-- this is basically default interface implementation
        print(self.view) <-- here we access a field of the concrete type, i.e. UIViewController
    }

}
t
No, maybe sealed classes can help you, or maybe use an abstract class with a final implementation of some method (im unsure what you mean)
i
no that's not it. I added an example in Swift of what I mean with some explanatory comments.
e
One way to do it in Kotlin is:
Copy code
interface ChildViewController<Self: UIViewController> {
    val self: Self
}

fun <Self: UIViewController> ChildViewController<Self>.foo() {
    println(self.view)
}
i
@elizarov thanks! I rewrote it using more familiar Android things:
Copy code
interface MyInterface<T: Fragment> {
    val self: T
}
fun <T: Fragment> MyInterface<T>.foo() {
    println(self.view)
}
But I still need to add a method to the class (
Fragment
) in this case to support this:
Copy code
override val self: RegisterFragment get() = this
Which is not as nice...