https://kotlinlang.org logo
Title
p

pawel.urban

09/12/2018, 9:43 AM
Hey. Can I have an extension function that would handle
SomeClass<X>
and
SomeClass<X?>
at once?
n

Nikky

09/12/2018, 9:47 AM
Nullable generics hmm.. i vaguely remember something there.. i will play around with it
p

pawel.urban

09/12/2018, 9:48 AM
I don’t like it as a permanent solution but for the safe of my refactoring it would help to to deduplicate a lot of code 🙂
n

Nikky

09/12/2018, 9:51 AM
does this work?
fun <T: Any> SomeClass<T?>.something()
r

robstoll

09/12/2018, 9:52 AM
do you need
?
explicitly?
otherwise you can just go with
X
without upper bound
which is the same as
X: Any?
n

Nicolas Chaduc

09/12/2018, 9:54 AM
It’s
SomeClass
why handle `T?`not the extension method.
n

Nikky

09/12/2018, 9:54 AM
i think you can go either way, not sure if that changes how it works, i would keep it seperated personally as a matter of taste.. type is one thing and the fact it could be nullable another
p

pawel.urban

09/12/2018, 9:55 AM
The issue is that I need something like
un <T: Any> SomeClass<T?>.something(): SomeClass<T or T?>
depending on extended class
I’ll try to work around, it would add too much language complexity even if possible.
n

Nikky

09/12/2018, 9:56 AM
and in case you want to use nonullable T in the function body like
value: T = argument ?: throw IllegalStateException()
might be possible (i don't think i ever tried though .. or i do not remember)
n

Nicolas Chaduc

09/12/2018, 9:58 AM
you need extension like that ?
SomeClass.myExtension<X?>()
1
d

diesieben07

09/12/2018, 9:59 AM
Please clarify, you want e.g.
SomeClass<String>
to yield
SomeClass<String?>
but
SomeClass<Int>
to yield
SomeClass<Int>
? Or what exactly do you want?
p

pawel.urban

09/12/2018, 10:08 AM
I have instances of a type of
SomeClass<String>
and
SomeClass<String?>
which I’d like to extend and the extension would accordingly return
SomeClass<String>
and
SomeClass<String?>
, depending on the extended type. I’m wondering if I can have just one extension in which internally I would handle potential nullability.
d

diesieben07

09/12/2018, 10:10 AM
"extended type" is very confusing in this context 😛 What you want is this:
fun <T> SomeClass<T>.foo(): SomeClass<T>
If you call
foo
on a
SomeClass<String>
it will return
SomeClass<String>
and if you call it on
SomeClass<String?>
it will return
SomeClass<String?>
.
If you need the type to be constrained, you can do:
fun <T : String?> SomeClass<T>.foo(): SomeClass<T>
- In this case only
String
or
String?
could be used for
T
.
p

pawel.urban

09/12/2018, 10:12 AM
let me try this one 🙂
This one seems to work fine 🙂