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


related this thread

i still unclear on distinction between these 2 definitions:

val foo = (arg: type) => {...}
def(arg:type) = {...}

as understand it:

1) val version bound once, @ compile time
single function1 instance created
can passed method parameter

2) def version bound anew on each call
new method instance created per call.

if above true, why 1 ever choose def version in cases operation(s) perform not dependent on runtime state?

for example, in servlet environment might want ip address of connecting client; in case need use def as, of course there no connected client @ compile time.

on other hand know, @ compile time, operations perform, , can go immutable val foo = (i: type) => {...}

as rule of thumb then, should 1 use defs when there runtime state dependency?

thanks clarifying

i'm not entirely clear on mean runtime state dependency. both vals , defs can close on lexical scope , hence unlimited in way. differences between methods (defs) , functions (as vals) in scala (which has been asked , answered before)?

you can parameterize def

for example:

object list {    def empty[a]: list[a] = nil     //type parameter alllowed here    val empty: list[nothing] = nil  //cannot create type parameter } 

i can call:

list.empty[int] 

but have use:

list.empty: list[int] 

but of course there other reasons well. such as:

a def method @ jvm level

if use piece of code:

trades filter iseuropean 

i choose declaration of iseuropean either:

val iseuropean = (_ : trade).country.region = europe 

or

def iseuropean(t: trade) = t.country.region = europe 

the latter avoids creating object (for function instance) @ point of declaration not @ point of use. scala creating function instance method declaration @ point of use. clearer if had used _ syntax.

however, in following piece of code:

val b = iseuropean(t) 

...if iseuropean declared def, no such object being created , hence code may more performant (if used in tight loops every last nanosecond of critical value)


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -