I'm asking a slight different question than this one. Suppose I have a code snippet:
def foo(i : Int) : List[String] = {
val s = i.toString + "!" //using val
s :: Nil
}
This is functionally equivalent to the following:
def foo(i : Int) : List[String] = {
def s = i.toString + "!" //using def
s :: Nil
}
Why would I choose one over the other? Obviously I would assume the second has a slight disadvantages in:
- creating more bytecode (the inner
def
is lifted to a method in the class) - a runtime performance overhead of invoking a method over accessing a value
- non-strict evaluation means I could easily access
s
twice (i.e. unnecesasarily redo a calculation)
The only advantage I can think of is:
- non-strict evaluation of
s
means it is only called if it is used (but then I could just use alazy val
)
What are peoples' thoughts here? Is there a significant dis-benefit to me making all inner val
s def
s?