https://kotlinlang.org logo
Title
k

karelpeeters

11/07/2018, 2:51 PM
val str = "hey"

when (val line = str) {
    "abc" -> println("abc")
    line.startsWith("h") -> println("starts with h")
}
Any reason this doesn't work? It says
Incompatible type: Boolean and String
on the
.startsWith
part.
m

MrNiamh

11/07/2018, 2:52 PM
It's comparing line with line.startsWith("h"), so "hey" and true/false
k

karelpeeters

11/07/2018, 2:52 PM
Of course 🤦‍♂️
😄 1
s

Spike Baylor

11/07/2018, 3:03 PM
for learning purposes, IS there a way to do what Karel is trying to do here?
k

karelpeeters

11/07/2018, 3:04 PM
I think you have to resort to doing something like this unfortunately:
val str = "hey"

when {
    str == "abc" -> println("abc")
    str.startsWith("h") -> println("starts with h")
}
👍 1
s

Spike Baylor

11/07/2018, 3:04 PM
ok thats what i was thinking. Not the end of the world
m

marstran

11/07/2018, 3:10 PM
What would this print if it were allowed? 🙂
val bool = false
when (val b = bool) {
  b == true -> println(1)
  else -> println(2)
}
Here,
b
is equal to the result of
b == true
, but
b == true
would be false. So the result would be ambigous.
k

karelpeeters

11/07/2018, 3:10 PM
Yeah of course, seems like I wasn't thinking straight.
m

marstran

11/07/2018, 3:11 PM
b == true -> println(1)
would both print and not print at the same time 😄 Schrödinger code
🐈 1
h

Hamza

11/07/2018, 4:22 PM
val str = "hey" when (val line = str) { "abc" -> println("abc") lstartsWith("h") -> println("starts with h") } Any
Remove line from line.startsWith()
k

karelpeeters

11/07/2018, 4:23 PM
That doesn't work unfortunately, that would try to call a function
startsWith
and compare
line
with the return value.
It would be cool if we could do
.startsWith("h")
or something.
e

Egor Trutenko

11/07/2018, 4:26 PM
Or we we had proper pattern-matching 🤔
®️ 2
k

karelpeeters

11/07/2018, 4:26 PM
Yeah
when
needs some upgrades.