https://kotlinlang.org logo
#announcements
Title
# announcements
i

Ian

04/17/2017, 10:37 PM
Trying to find a better pattern. Have some code like this:
Copy code
var s : String? = null
exec {
    s = createS()
}
s!!.doSomething()
the
exec
block is executed synchronously so
s
will be assigned to a non-null value, but the type system doesn’t know this hence the
!!
.
createS()
can only be called within the
exec
block. Obviously the
!!
is ugly, I’m trying to figure out whether there is a better way to get
s
“out” of the inner code block. I could modify
exec
such that it will return whatever is returned by the code block, but what if I need to get multiple variables out of the code block?
u

umar

04/18/2017, 4:16 AM
ianclarke: maybe you need to return data class from `exec`:
Copy code
data class Data(val str: String, val num: Double)
So you can use as normal class:
Copy code
val data = exec  {
  Data(str = createS(), num = createD())
}
data.str.doSomething()
data.num.doSomething()
Or destructure it immediately:
Copy code
val (str, num) = exec  {
  Data(str = createS(), num = createD())
}
str.doSomething()
num.doSomething()
i

Ian

04/18/2017, 5:23 AM
Yes, I’ve been playing around and I’m thinking that just returning a single value through exec might be sufficient - it constrains some things but possibly in a good way. Thanks for your help 🙂
u

umar

04/18/2017, 5:45 AM
You're welcome