3 ms·
It seems very similar to Scala in several ways (var, def etc), but the way to declare immutable fields is different from Scala Scala val x:Int = 10 // Immut
by octo_t 14y ago
It seems very similar to Scala in several ways (var, def etc), but the way to declare immutable fields is different from Scala
Scala
val x:Int = 10 // Immutable
var x:Int = 10 // Mutable
def x:Int = 10 // function
Virgil
def x:Int = 10 // Immutable + function
var x:Int = 10 // Mutable
I think I prefer Virgils method, it feels much purer to me, in keeping with functions as first class members, but I'm not sure how it would handle mutable datastructures.
- ismarc 14y agoIt's actually more complex than that. You can use val and def in the same places. The difference is when it is evaluated. val has the right hand side evaluated immediately (such as, if it's a class member, it will be evaluated when the class is constructed). def has the right hand side evaluated every time it is referenced. So, val x = 5+5 would evaluate 5+5 and assign to x. def x = 5+5 would set x to a function that takes no parameters and returns an int, but if you had, say x + x, that function would be called twice, resulting in a value of 20. This difference is stark when you look at what it's doing, but allows for some interesting uses when combined with lazy vals. We use it pretty extensively in our configuration loader (using twitter-eval) that allows us to do per-value overrides of configuration files by using lazy vals assigned to defs and then using the defs in the application (of all the performance bottlenecks we have, the possibly optimized out function call generated for the defs is negligible). The end result is that you can derive values from configuration settings prior to the configuration finishing being loaded. This means we don't have to care what order the configuration files are loaded in (they're separated by what they're configuring, with many shared between applications).