is there a way to do a computation inside a `when`...
# announcements
n
is there a way to do a computation inside a
when
block?
Copy code
return if (string == null) null
        else {
            val id = Json.parse(string)?.asObject()?.get("id")
            when {
                id == null -> null
                id.isString -> Util.entry(id.asString(), string)
                else -> Util.entry(id.asObject(), string)
            }
        }
here, i first check a
if
then compute the
id
then execute my
when
using the computed
id
it feels not as readable as it could
a
Maybe this feels ok?
Copy code
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)
}
Welp, nevermind the syntax is only for sth like switch statements (matches with elements instead), it won't allow condition checks.
n
no worries thanks for the try
m
I like this (might need minor corrections to be compilable)
Copy code
val id = string?.let(Json::parse)?.asObject()?.get("id")
    return when (id?.isString) {
        null -> null
        true -> Util.entry(id.asString(), string)
        false -> Util.entry(id.asObject(), string)
    }
also, if
isString
didn't return Boolean? but rather Boolean, I would do
Copy code
val id = string?.let(Json::parse)?.asObject()?.get("id") ?: return null
    return if(id.isString) Util.entry(id.asString(), string) else Util.entry(id.asObject(), string)
🤔 1
n
thanks @Milan Hruban i’ll try how it looks in intellij
👋 1
m
let me know if it worked, so I can learn too:)
👍 1
n
good news: code works on the readability side, i’m less happy
🙁 1