i’d like to put everything in the `when` but then,...
# announcements
n
i’d like to put everything in the
when
but then, how do i compute the
id
so i can use it in the later evaluations?
v
How about this?
Copy code
val id = string?.let { Json.parse(it) }?.asObject()?.get("id")
return when {
    id == null -> null
    id.isString -> Util.entry(id.asString(), string)
    else -> Util.entry(id.asObject(), string)
}
k
Could do: when (something) No?
v
Not in this case
s
What about
Copy code
when(val id =...) {
    ...
}
v
I don't think you would win much. This could be used to restrict the scope of
id
, but the
when
result is directly returned, so there is nothing the
id
could leak into. Besides that whyever, then
id
cannot be smart-casted to not-null in the second branch, but you need
Copy code
return when(val id = string?.let { Json.parse(it) }?.asObject()?.get("id")) {
    id == null -> null
    id!!.isString -> Util.entry(id.asString(), string)
    else -> Util.entry(id.asObject(), string)
}
or
Copy code
return when(val id = string?.let { Json.parse(it) }?.asObject()?.get("id")) {
    id == null -> null
    id?.isString -> Util.entry(id?.asString(), string)
    else -> Util.entry(id?.asObject(), string)
}
or similar. But I think this is more a compiler bug.
n
thanks for your help folks 🙂
v
Nah, it is not a compiler bug and it also cannot work
if you have
when(val ...) { ... }
then the subject is captured as that
val
so that you can use it within the branches easily, but the when expression variant would still be the one with parameter and thus you cannot use arbitrary expressions but only supplying values or ranges that are compared or checking types and as it is not
is String
but
.isString
you need the parameterless variant