```final boolean b; final double d; { final Ra...
# announcements
j
Copy code
final boolean b;
final double d;
{
    final Random rng = new Random();
    final double r = rng.nextDouble();
    if (r < 0.5d) {
        b = false;
        d = r / 2;
    } else {
        b = true;
        d = r * 3;
    }
    // rng and r fall out of scope
}
Is it possible to express this in kotlin? using a run {} "block" is a lambda, and captured value initialization is forbidden.
m
Use an
init
block.
Something like this:
Copy code
val b:Boolean
val d:Double

init {
    val rng = Random()
    val r = rng.nextDouble()
    if (r < 0.5) {
        b = false
        d = r / 2
    } else {
        b = true
        d = r * 3
    }
}
j
init is only valid grammar for a class, correct? what about inside a function?
m
That's right. Hmm
n
Copy code
fun main(args: Array<String>) {
    var b: Boolean
    var d: Double

    {
        val rng = Random()
        val r = rng.nextDouble()
        if (r < 0.5) {
            b = false
            d = r / 2
        } else {
            b = true
            d = r * 3
        }
    }()
}
though not sure why you’d want it like that?
j
In this case you could sort of fake it by destructuing a pair, but lets say you had > 3 initializations to do
m
That doesn't work @neil.armstrong. You get this compiler error: "Captured values initialization is forbidden due to possible reassignment".
n
ahh
j
@neil.armstrong In that code they are var, not val
n
true
m
Ah, didn't see the
var
.
But is it really that important for
rng
and
r
to leave the scope?
j
This is a really contrived example. In truth I have some fairly heavyweight object that is recycled in an object pool
I have to call the recycle method on it, and using it after that is a runtime error