|
|
|
|
|
by ismarc
4811 days ago
|
|
It'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). |
|