https://kotlinlang.org logo
Title
d

Daniele Segato

09/14/2018, 4:18 PM
Exactly when I tough i was getting pro at kotlin I fall on the most basic thing... this code below do not compile 🙂 I know about ranges... I can do
in Int.MIN_VALUE until 0
I also know I can save the value and compare to 0 using a
when
with no parameter. But are these really the only ways? Can't I do something similar to the code below? And to check !0 with ranges I would have to write:
!in in 1..Int.MAX_VALUE && !in -1 downTo Int.MIN_VALUE
But this doesn't look right, there must be another way, right?
a

Andreas Sinz

09/14/2018, 4:22 PM
Only
in
,
is
or a comparison
==
with an expression is supported by
when
right now
d

Daniele Segato

09/14/2018, 4:26 PM
😞 so what I wrote is actually the only way except
-1 downTo Int.MIN_VALUE
is converted into 2 comparison while
x < 0
would be only 1
s

Shawn

09/14/2018, 4:26 PM
why not just
have an if/else here
a

Andreas Sinz

09/14/2018, 4:27 PM
or use
when
differently:
val x = functionReturningInteger()
when {
    x < 0 -> { }
    x > 0 -> { }
   ...
}
d

Daniele Segato

09/14/2018, 5:32 PM
yes, I did that too.. slightly differently
functionReturningInteger().let{ when { .... } }
i almost never use
val = ...
in my code, I usually prefer using let, apply, with and so on... not sure if that's a good idea
s

Shawn

09/14/2018, 5:34 PM
if you do so at the expense of your code’s readability, then it’s a terrible idea
there’s nothing wrong with assigning some variables here and there if it makes the relevant block easier to comprehend
the problem is unnecessary noise, not assignments at large
d

Daniele Segato

09/14/2018, 5:35 PM
I don't know, i like this more:
return day.compareTo(other.day).let { if (it != 0) it else time.compareTo(time) }
then this:
val comparison = day.compareTo(other.day)
return if (comparison != 0) comparison else time.compareTo(time)
is it just me?
s

Shawn

09/14/2018, 5:37 PM
in that case I’d say that repeating
comparison
over and over isn’t making it easier to read
it’s not an indictment of
val x = ...
as a whole
just an example of where it doesn’t make things clearer
maybe something like this would read a bit more naturally
return day.compareTo(other.day)
        .takeIf { it != 0 }
        ?: time.compareTo(other.time)
👍 3
a

Alowaniak

09/14/2018, 7:56 PM
Well in that particular case you should be able to do something like
compareBy({it.day},{it.time}).compare(this,other)
afaict Or compareValuesBy or w/e
d

Daniele Segato

09/14/2018, 11:33 PM
Ah!!
takeIf
i didn't know about... Is there a list of all of this? Thanks by the way. Also didn't know about compareBy!
I knew let, use, apply, also and with :-) but couldn't find a list with all