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

joelpedraza

09/27/2017, 1:59 PM
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

marstran

09/27/2017, 2:03 PM
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

joelpedraza

09/27/2017, 2:06 PM
init is only valid grammar for a class, correct? what about inside a function?
m

marstran

09/27/2017, 2:07 PM
That's right. Hmm
n

neil.armstrong

09/27/2017, 2:08 PM
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

joelpedraza

09/27/2017, 2:09 PM
In this case you could sort of fake it by destructuing a pair, but lets say you had > 3 initializations to do
m

marstran

09/27/2017, 2:10 PM
That doesn't work @neil.armstrong. You get this compiler error: "Captured values initialization is forbidden due to possible reassignment".
n

neil.armstrong

09/27/2017, 2:10 PM
ahh
j

joelpedraza

09/27/2017, 2:10 PM
@neil.armstrong In that code they are var, not val
n

neil.armstrong

09/27/2017, 2:10 PM
true
m

marstran

09/27/2017, 2:10 PM
Ah, didn't see the
var
.
But is it really that important for
rng
and
r
to leave the scope?
j

joelpedraza

09/27/2017, 2:12 PM
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
2 Views