Kotlin idiom equivalent to Go Language If,Switch initialization statement


#1

The Go language has a pretty useful idiom (I think) that allows you to define some variable local to   the "If" or "Switch" statement in the initialization part of the statement(see here for reference https://golang.org/doc/effective_go.html#if ) For example suppose that I want to check that some value is in some specific non trivial range (i.e. the range bounds are the result of some calculation/function call) in kotlin I need to write

val rangeMin=calculateRangeMin()
val rangeMax=calculateRangeMax()
if(myValue !in rangeMin..rangeMax) throw IllegalArgumentException("myvalue $myValue out of range $rangeMin .. $rangeMax")

What  I want to do is basically define some variable local to the "if" statement, that will be used multiple time inside the statement, but will never used outside it. In Go this idiom is used a lot for processing possible error return values from some function. Idiomatic Go does not rely on exception based error handling, and any language supporting functional programming should also do the same. This feature in Go is probably kind of a legacy from C/C++, where you can have assignments inside an expression. In C/C++ you would be able to write something like this (**)

if( myValue<(rangeMin=calculateRangeMin()) || myValue>(rangeMax=calculateRangeMax) ) ...

in an hypothetical Kotlin/C++/Go hybrid it would be nice if I would be able to write something

if(myValue !in range:=calculateRangeMin()..calculateRangeMax() ) throw IllegalArgumentException("myvalue $myValue out of range ${range)")

Do you think there is a (SIMPLE) way to implement something similar to what I want with current Kotlin syntax/features?

NOTES:
(**)= well not really… only if rangeMin and rangeMax variables where already defined before the “if” statement


#2

This is how you can do it in Kotlin:

calculateRangeMin()..calculateRangeMax() let { range -> if (myValue !in range) throw IllegalArgumentException("myvalue $myValue out of range $range") }
 
// or the short version
calculateRangeMin()..calculateRangeMax() let { if (myValue !in it) throw IllegalArgumentException("myvalue $myValue out of range $it") }

#3

Thank you Ioannis. That was exactly what I was searching for. I hope that Jetbrains will better document use cases for all the good stuff in the standard library