https://kotlinlang.org logo
#announcements
Title
# announcements
t

Tim Kuzmin

07/21/2019, 1:49 PM
Hey guys! I very like kotlin cause it’s very agile for the most situation f.e. I wanna have postfix version for ternary operator(i understand position of lang-developers about if-else). So, that’s my first solution:
Copy code
fun <T> Boolean.ternary(first: T, second: T) =
        if (this) first
        else second
Any pro-programmer will tell u that in cases like this
(stringA != null).ternary(stringA!!, stringB!!)
we will have npe(parameters of function calculates before call). Lets make our function inline and add reified type:
Copy code
inline fun <reified T> Boolean.ternary(first: T, second: T) =
        if (this) first
        else second
Nice! Now for non-primitives classes we will not have any trouble. I guess u’ve already understand what I mean. For primitives it doesnt work, cause even for inline function kotlin calculates primitive expressions and then call function. For me it’s looks like a bug. Does anybody know will it be fixed for next versions?
d

Dominaezzz

07/21/2019, 1:50 PM
I think you need a contract.
I haven't written one myself but you can look at the implementation of
requireNonNull
for inspiration.
Actually nevermind, it'll only work if
first
and
second
are lambdas.
t

Tim Kuzmin

07/21/2019, 1:55 PM
thank u, will research solution in this area 🙂
Contracts doesnt fix issues this type, it’s not kotlin compiler sugar-fix. This problem as I think is a little bit deeper than it’s seems
k

karelpeeters

07/21/2019, 7:18 PM
Neither
inline
nor
reified
have any effect on when the parameters are evaluated, so I don't understand what you're talking about. It doesn't matter whether T is primitive either.
If you want lazy evaluation you definitely need lambda parameters.
5 Views