elect
September 28, 2016, 6:22pm
1
First of all, Kotlin is awesome!
Second, it’d be cool if we could have something similar to smart cast, that is declaring a val (thread safe) inside the if statement and use it directly in the body
if( val email = client?.personalInfo?.email != null && message!=null) mailer.sendMessage(email, message)
1 Like
jhoak
September 29, 2016, 1:08am
2
I’m not really a language expert, but that just seems harder to read while you’re only saving one line of code. I’d prefer putting the email initialization right above that.
yole
September 29, 2016, 11:06am
3
You can use the let function for this purpose:
client?.personalInfo?.email?.let { email ->
if (message != null) mailer.sendMessage(email, message)
}
3 Likes
That would be wonderful:
if (val value = this.Value; value is Type) {
}
kyay10
October 19, 2025, 9:55pm
5
Just use a let:
this.Value.let { value ->
if (value !is Type) return@let
...
}
Landei
October 19, 2025, 10:14pm
6
In this specific case, I would write:
this.Value
.let{ it as? Type }
?.let { value -> ... }
kyay10
October 19, 2025, 10:15pm
7
Or even:
(this.Value as? Type)?.let { value ->
...
}
1 Like
Varia
October 20, 2025, 10:56am
8
Or even
val value = this.Value; if (value is Type) {
…
}
I am very much in favor of preferring the most basic syntax unless there are significant advantages to the more creative alternatives.
1 Like
Landei
October 20, 2025, 8:38pm
9
How about a little helper function?
inline fun <reified T> Any.ifType(crossinline body : (T) -> Unit) {
if (this is T) {
body(this)
}
}
Usage: this.Value.ifType<Type>{ v -> ... }