Hello everyone, I'm guessing this is impossible b...
# multiplatform
h
Hello everyone, I'm guessing this is impossible but I would really like it if it was possible. I have a case where I end up having to write a lot of similar code, and I'm wondering if there's a way to simplify it. I have a series of interfaces that each are supertypes of a base interface, and they each have useful features over the base interface, so I want to retain that information when writing extension functions for those types. For example:
Copy code
interface Foo
interface Foo2 : Foo

interface Bar : Foo
interface Bar2 : Bar
I end up writing a lot of functions like this:
Copy code
fun Foo.baz(): Foo
fun Foo2.baz(): Foo2

fun Bar.baz(): Bar
fun Bar2.baz(): Bar2
Where
baz()
has essentially the same implementation for each overload, but they only differ in maintaining type information. I'm wondering if there's a way to define generic type parameters that default to the highest subtype it can find. I'm not sure what the syntax would be but it would do something like this:
Copy code
fun <T : Foo, R> T.baz(): R
	where R is Foo2 if T is Foo2,
	or R is Bar2 if T is Bar2,
	or R is Bar if T is Bar,
	else R is Foo
Like I said, probably impossible but would be really nice. Edit: I should probably also mention that the function signature
Copy code
fun <T : Foo> T.baz(): T
is impossible for my case, because I can't return the concrete type. I only have the ability to return the interface.
p
why not just
fun <T: Foo> T.baz(): T
?
h
@phldavies Yeah I should have specified that won't work for my case because I don't have a way to return the concrete type, I can only return the interface. It's a bit of a weird case but it's a definite restriction I have.
c
Alternative solution (though it's not great): put the function in the interface, and override it everywhere providing a more concrete type. That's what I do e.g. here.