Post History
Making a function with val can be shorter than with a def If you're pattern matching, you can use Scala's special syntax and omit match when assigning an anonymous function to a val. As you can se...
Answer
#1: Initial revision
# Making a function with `val` can be shorter than with a `def` If you're pattern matching, you can use Scala's special syntax and omit `match` when assigning an anonymous function to a `val`. As you can see, it's a lot shorter: ```scala val g:List[Int]=>Int={case h::t=>h+g(t)case _=>0} def f(l:List[Int]):Int=l match{case h::t=>h+f(t)case _=>0} ``` You can also use underscore syntax. For certain functions, this is always profitable. For others, like the example below, where the type of the parameter cannot be inferred, it is only profitable when you have only one parameter with a type ascription. ``` val g=(_:Int)+1 def f(i:Int)=i+1 ``` However, if you need to reuse a function, make a `def` instead of a `val`. Consider these two pairs of functions: ```scala //Recursive def f(i:Int):Int=if(i>0)i*f(i-1)else 1 val f:Int=>Int=i=>if(i>0)i*f(i-1)else 1 //Non-recursive functions are also shorter with def def f(i:Int)=i+1 val g=(i:Int)=>i+1 ```