Is there any way to create nonlocal variables in Kotlin ? (if not, any plans ?)
Take the following example:
fun getSomething(): {
val time = measureTimeMillis {
val result = client.get { url("example.com") }
}
this.logger("Took $time")
return result // this doesn't work since result is not available in this scope
}
I would like to be able to create the variable result in the scope of measureTimeMills and return it in the function getSomething without having to declare a var as null and reassigning it in the block.
Otherwise what would be the best way to handle those situations ?
What I really ended up doing is create a measureTimeMillis that returns the result and the time it took but I was still curious to know if it is possible to create nonlocal variables in any way
Non-local variables are not supported. You could work around them using wrapper objects that you pass to the function that sets the value. But this makes it less readable and introduces the possibility for null (which can be resolved using the upcoming contracts):
class Wrapper<T> {
val value: T? = null
}
fun getSomething(): Response {
val result = Wrapper<Response>()
val time = measureTimeMilliis {
result.value = client.get { url("example.com") }
}
this.logger("Took $time")
return result.value!!
}
Adding support for non-local variables would significantly change the semantics of Kotlin, so I think this is something that won’t be added.
Thank you all for your answers. I like to avoid declaring a var as null and then reassigning it. In my code I had the function that @lamba92 suggested. But this meant I couldn’t use the std library measureTimeMillis. So I was still curious to know if there was a way to declare nonlocal variables which as I understood is not possible in Kotlin .