There should be a way to specify that a function’s...
# language-proposals
m
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
Is that not possible already?
m
I don’t know any way to achieve that 🤔
d
You mean the
where Int : R
part?
What is the point of this? What is the use case?
m
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
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
Nope, that won’t work either:
Type parameter cannot have any other bounds if it’s bounded by another type parameter
d
well, good try I guess