Exactly when I tough i was getting pro at kotlin I...
# getting-started
d
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
Only
in
,
is
or a comparison
==
with an expression is supported by
when
right now
d
😞 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
why not just
have an if/else here
a
or use
when
differently:
Copy code
val x = functionReturningInteger()
when {
    x < 0 -> { }
    x > 0 -> { }
   ...
}
d
yes, I did that too.. slightly differently
Copy code
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
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
I don't know, i like this more:
Copy code
return day.compareTo(other.day).let { if (it != 0) it else time.compareTo(time) }
then this:
Copy code
val comparison = day.compareTo(other.day)
return if (comparison != 0) comparison else time.compareTo(time)
is it just me?
s
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
Copy code
return day.compareTo(other.day)
        .takeIf { it != 0 }
        ?: time.compareTo(other.time)
👍 3
a
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
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