Allow to declare directly `val` in the `if` statement and use in body

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

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.

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) {

}

Just use a let:

this.Value.let { value ->
  if (value !is Type) return@let
  ...
}

In this specific case, I would write:

this.Value
  .let{ it as? Type }
  ?.let { value -> ... }

Or even:

(this.Value as? Type)?.let { value ->
  ...
}
1 Like

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

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 -> ... }