Reputation: 105258
I have a val
:
val something = System.nanoTime
that then goes through a series of method calls:
foo(something) {
bar(something, 2) { etc }
}
I'd like to defer val
resolution until a very last method that actually does something with it. I'm aware of scala's lazy
modifier, but it seems that passing something
as a parameter automatically resolves it's value, regardless if the variable is being used or not inside that method.
My (somewhat ugly) solution so far is:
val something = () => System.nanoTime
Although this works, it involves changing all the method signatures, in this case from Long
to () => Long
. I guess there might be a more elegant way of solving it, what do you guys think?
Upvotes: 3
Views: 236
Reputation: 24403
It's not possible to do this without changing the signatures, however you should use x: => Long
instead of x: () => Long
. The first is a so called by name parameter
. A by name parameter will be evaluated, every time you call it. So in total it would look like:
def foo(x: => Long) = {
x + 12 // x will be evaluated here
}
lazy val x = 12L
foo(x)
Upvotes: 6