https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
m

Marc Knaup

02/07/2020, 8:45 AM
There should be a way to specify that a function’s type parameter is contravariant. Example:
Copy code
inline fun <R> Any.toIntOrElse(elseBlock: () -> R): R where Int: R = …
should allow
Int
,
Int?
,
Any
and
Any?
as
R
.
s

stantronic

02/07/2020, 10:56 AM
Is that not possible already?
m

Marc Knaup

02/07/2020, 10:57 AM
I don’t know any way to achieve that 🤔
d

Dico

02/07/2020, 3:10 PM
You mean the
where Int : R
part?
What is the point of this? What is the use case?
m

Marc Knaup

02/07/2020, 3:34 PM
If
R
is nullable then the result of the function becomes nullable too. Or if I want to return for example
Number
in the else block the result widens from
Int
to
Number
. If you have
Int
the benefits of widening are limited, but they larger the hierarchy the more useful it becomes. Nullable vs. non-nullable is main use-case though. I ran into that problem several times now.
d

Dico

02/07/2020, 4:12 PM
I did not mean to also send that to channel, sorry
If you want to return
Number
instead of
Int
then the result should simply be
Number
.
Same with
Any
instead of
Number
Perhaps you can do this:
Copy code
fun <R, T> Any.toIntOrElse(elseBlock: () -> R): R
   where T : R, T : Int {...}
m

Marc Knaup

02/08/2020, 8:22 AM
Nope, that won’t work either:
Type parameter cannot have any other bounds if it’s bounded by another type parameter
d

Dico

02/08/2020, 8:23 AM
well, good try I guess
2 Views