I love how `when` cleans up my code. Used with `in...
# announcements
h
I love how
when
cleans up my code. Used with
in
, checking if an element is in a collection is very simple. Now have I overlooked the possibility of doing it the other way around? I.e. is it possible to do something like this (pseudo-code):
Copy code
when (collection-of-strings) {
  has "string 1" -> handleString1()
  has "string 2" -> handleString2()
  has "string 3" -> handleString3()
  else -> throw Exception()
}
🚫 1
😍 1
f
You can do something like this :
Copy code
with(collection-of-strings) {
        when {
            contains("string 1") -> handleString1()
            contains("string 2") -> handleString2()
            contains("string 3") -> handleString3()
            else -> throw Exception()
        }
    }
not as clean though
o
One problem is that in
when
first match wins, and semantics here is not clear. Should it “handle” every element in a collection, or just first match?
👏 1
👍 1
Also lookup for each check is not optimal, obviously, especially when collection has O(n)
contains
h
@fred.deschenes It may not be as consise as my wish-for example, but it still is a huge win vis-à-vis of the endless
if {} else if ...
that we did in java ...! Thanks for pointing it out!
f
@hallvard np, but keep in mind what @orangy mentioned above
h
@orangy Good points, thanks.
o
There is also a proposal to generate better
switch
with
invokedynamic
for Java: http://mail.openjdk.java.net/pipermail/amber-spec-observers/2018-April/000568.html This can be done manually in your case by using something like
Copy code
when(listOfStrings.indexOfWhich("a", "b", "c")) {
 0-> // a
 1-> //b
}
indexOfWhich
can be implemented efficiently, but there is no such function in stdlib currently