scala - What's the difference between these two ways to declare functions? -


follow 2 similar functions, a , b, declared differently:

scala> val = { x:int => x+x } a: int => int = <function1>  scala> def b(x:int) = x+x b: (x: int)int 

the difference can find between 2 def function can specify parameter's name pass (e.g. b(x=1)). how these functions different in other regards? should used when?

edit:

i not able use @tailrec annotation val method.

the principal difference in how scala translates definitions. in scala lambda (an anonymous function, function value, function literal) , method different things. first definition of yours sugar instance of function1 class, 1 of classes used lambdas, second method of surrounding object, compiles standard java method.

the practical difference between 2 scala cannot let refer method value, renders second class citizen. results in redundant indirections when dealing higher order functions. e.g., following:

1.to(4).map(b) 

desugars wrapper lambda:

1.to(4).map((x: int) => b(x)) 

which sugar for:

1.to(4).map(   new function1[int, int] {     def apply(x: int): int = b(x)   } ) 

feels quite redundancy, right? why if intention function used first class citizen (i.e., being passed around value) more reasonable declare lambda beginning.


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

ios - Change Storyboard View using Seague -

verilog - Systemverilog dynamic casting issues -