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
thana
01/16/2020, 2:01 PM
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
iex
01/16/2020, 5:23 PM
no that's not it. I added an example in Swift of what I mean with some explanatory comments.
e
elizarov
01/17/2020, 8:20 AM
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
iex
01/17/2020, 4:02 PM
@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)
}