Apparently I'm a Kotlin nab. How do I get somethin...
# announcements
b
Apparently I'm a Kotlin nab. How do I get something like this working? I'm looking for a way to combine two interfaces that are from external libs.
j
Why don’t you make your MyAdaptor class implement FilterableAdaptor?
b
MyAdapter is also coming from a library that I don't control, so it doesn't have access to that interface.
j
Ok so MyAdapter is probably not a good name for it 🙂 In general I’d be careful around combining interfaces (Interface segregation principle.) You could try creating your own concrete type of FilterableAdaptor that delegates to MyAdapter using delegation or composition.
p
It's at point like this when I wish you could use a typealias for this type of thing, but your can't
j
I feel like what this is asking for is something like Typescript’s structural typing.
e
in this case an intersection type could work, but there's no way to denote it directly... https://youtrack.jetbrains.com/issue/KT-13108
but if it's a function argument, there's an old Java trick like
fun <T> foo(filterableAdapter: T) where T : Adapter, T : Filterable
b
@johnaqel Yeah,
MyAdapter
was not the most correct name indeed.
@ephemient Oh cool, that's a nice little trick. Unfortunately, I need to use it beyond just a function. Here is a more complete example.
I suppose I can just use an
Any
for the adapter in my class and cast it as necessary. It looks like the function works well to force the user of the class to pass the required type.
e
one possible type-safe workaround:
Copy code
var adapter: Adapter? = null
var filterable: Filterable? = null
fun <T> setAdapter(adapter: T) where T : Adapter, T : Filterable {
    this.adapter = adapter
    this.filterable = adapter
}
and then use the right variable depending on which interface you need at that point. of course it's a pain and it would be nice if we could properly denote intersection types, but oh well
b
That's actually a pretty clean solution! Works for me!
Thanks again for the help.
r
you can use where with class type arguments too, not just function ones, so alternative could be smth like this
Copy code
interface Adapter {
    fun adapterFun()
}

interface Filterable {
    fun filterableFun()
}

class SearchPage<FilterableAdapter>
    where FilterableAdapter : Adapter, FilterableAdapter : Filterable {

    private var adapter: FilterableAdapter? = null

    fun setAdapter(adapter: FilterableAdapter) {
        this.adapter = adapter
    }

    fun test() {
        adapter?.adapterFun()
        adapter?.filterableFun()
    }
}
but yea, intersection types would be great for this
b
Oh sweet, that's also a pretty clever solution!