3 ms·
Unfortunately, this conflicts with the (common, good) advice to make as many variables final / const as possible, since it separates the declaration of a variab
by bkirwi 12y ago
Unfortunately, this conflicts with the (common, good) advice to make as many variables final / const as possible, since it separates the declaration of a variable and its assignment.
One nice thing that falls out of Scala's syntax is that it makes this style possible without using mutation:
val result1 = {
val bar = barFromFoo1(foo)
// ...
baz.awesome()
}
val result2 = {
val bar = ... // unrelated to 'bar' above
bar.awesome()
}
All names introduced in the block go out of scope at the end of the block, but the 'value' of the block is just the value of the last line, so you can assign the whole thing to a final / constant variable. This style has all the advantages listed above, and makes it easier to avoid mutation and having uninitialized variables in scope -- I wish more languages had it.
- jxm262 12y ago+1 for this. I'm still pretty new to Scala, but coming from my day job (Java) , I'm finding more and more reasons to love it. As a side note, I'd love to see Scala make it's way into game development. I've been messing around trying to get libgdx working with it. But I would love something that lets me take full advantage of the Scala language.
- salmonellaeater 12y ago> Unfortunately, this conflicts with the (common, good) advice to make as many variables final / const as possible, since it separates the declaration of a variable and its assignment. In Java you can separate the declaration and assignment of a final variable as long as every branch provably assigns to the variable. For example: final int x; if(someCondition) { final int a = 1; final int b = 2; x = a + b; } else { x = 0; }
- bkirwi 12y agoI did not know this; thanks! I think I still prefer Scala's structural style, but I'll definitely have good use for this when I wander back into the Java universe.