```val str = "hey" when (val line = str) { "a...
# announcements
k
Copy code
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
It's comparing line with line.startsWith("h"), so "hey" and true/false
k
Of course 🤦‍♂️
😄 1
s
for learning purposes, IS there a way to do what Karel is trying to do here?
k
I think you have to resort to doing something like this unfortunately:
Copy code
val str = "hey"

when {
    str == "abc" -> println("abc")
    str.startsWith("h") -> println("starts with h")
}
👍 1
s
ok thats what i was thinking. Not the end of the world
m
What would this print if it were allowed? 🙂
Copy code
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
Yeah of course, seems like I wasn't thinking straight.
m
b == true -> println(1)
would both print and not print at the same time 😄 Schrödinger code
🐈 1
h
val str = "hey" when (val line = str) { "abc" -> println("abc") lstartsWith("h") -> println("starts with h") } Any
Remove line from line.startsWith()
k
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
Or we we had proper pattern-matching 🤔
®️ 2
k
Yeah
when
needs some upgrades.