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)

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