https://kotlinlang.org logo
Title
h

hallvard

05/29/2018, 1:41 PM
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):
when (collection-of-strings) {
  has "string 1" -> handleString1()
  has "string 2" -> handleString2()
  has "string 3" -> handleString3()
  else -> throw Exception()
}
😍 1
🇳🇴 1
f

fred.deschenes

05/29/2018, 1:46 PM
You can do something like this :
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

orangy

05/29/2018, 1:46 PM
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

hallvard

05/29/2018, 1:49 PM
@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

fred.deschenes

05/29/2018, 1:49 PM
@hallvard np, but keep in mind what @orangy mentioned above
h

hallvard

05/29/2018, 1:50 PM
@orangy Good points, thanks.
o

orangy

05/29/2018, 1:52 PM
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
when(listOfStrings.indexOfWhich("a", "b", "c")) {
 0-> // a
 1-> //b
}
indexOfWhich
can be implemented efficiently, but there is no such function in stdlib currently