Scala: val foo = (arg: Type) => {...} vs. def(arg:Type) = {...}

function, immutability, runtime, scala, state

Solution

I'm not entirely clear on what you mean by runtime state dependency. Both `val`s and `def`s can close over their lexical scope and are hence unlimited in this way. So what are the differences between methods (`def`s) and functions (as `val`s) in Scala (which has been asked and answered before)?

You can parameterize a def

For example:

object List {

  def empty[A]: List[A] = Nil     //type parameter alllowed here

  val Empty: List[Nothing] = Nil  //cannot create a type parameter
}

I can then call:

List.empty[Int]

But I would have to use:

List.Empty: List[Int]

But of course there are other reasons as well. Such as:

A def is a method at the JVM level

If I were to use the piece of code:

trades filter isEuropean

I could choose a declaration of `isEuropean` as either:

val isEuropean = (_ : Trade).country.region = Europe

Or

def isEuropean(t: Trade) = t.country.region = Europe

The latter avoids creating an object (for the function instance) at the point of declaration but not at the point of use. Scala is creating a function instance for the method declaration at the point of use. It is clearer if I had used the `_` syntax.

However, in the following piece of code:

val b = isEuropean(t)

...if `isEuropean` is declared a `def`, no such object is being created and hence the code may be more performant (if used in very tight loops where every last nanosecond is of critical value)

Problem

Related to this thread I am still unclear on the distinction between these 2 definitions: `val foo = (arg: Type) => {...}` `def(arg:Type) = {...}` As I understand it: 1) the val version is bound once, at compile time a single Function1 instance is created can be passed as a method parameter 2) the def version is bound anew on each call new method instance created per call. If the above is true, then why would one ever choose the def version in cases where the operation(s) to perform are not dependent on runtime state? For example, in a servlet environment you might want to get the ip address of the connecting client; in this case you need to use a def as, of course there is no connected client at compile time. On the other hand you often know, at compile time, the operations to perform, and can go with immutable `val foo = (i: Type) => {...}` As a rule of thumb then, should one only use defs when there is a runtime state dependency? Thanks for clarifying

Original source

Related problems