Hunter
07/31/2025, 5:19 PMinterface Foo
interface Foo2 : Foo
interface Bar : Foo
interface Bar2 : Bar
I end up writing a lot of functions like this:
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:
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
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.phldavies
07/31/2025, 5:22 PMfun <T: Foo> T.baz(): T
?Hunter
07/31/2025, 5:24 PMCLOVIS
08/01/2025, 7:51 AM