scala - What is the difference between "def" and "val" to define a function -


what difference between:

def even: int => boolean = _ % 2 == 0 

and

val even: int => boolean = _ % 2 == 0 

both can called even(10).

method def even evaluates on call , creates new function every time (new instance of function1).

def even: int => boolean = _ % 2 == 0 eq //boolean = false  val even: int => boolean = _ % 2 == 0 eq //boolean = true 

with def can new function on every call:

val test: () => int = {   val r = util.random.nextint   () => r }  test() // int = -1049057402 test() // int = -1049057402 - same result  def test: () => int = {   val r = util.random.nextint   () => r }  test() // int = -240885810 test() // int = -1002157461 - new result 

val evaluates when defined, def - when called:

scala> val even: int => boolean = ??? scala.notimplementederror: implementation missing  scala> def even: int => boolean = ??? even: int => boolean  scala> scala.notimplementederror: implementation missing 

note there third option: lazy val.

it evaluates when called first time:

scala> lazy val even: int => boolean = ??? even: int => boolean = <lazy>  scala> scala.notimplementederror: implementation missing 

but returns same result (in case same instance of functionn) every time:

lazy val even: int => boolean = _ % 2 == 0 eq //boolean = true  lazy val test: () => int = {   val r = util.random.nextint   () => r }  test() // int = -1068569869 test() // int = -1068569869 - same result 

performance

val evaluates when defined.

def evaluates on every call, performance worse val multiple calls. you'll same performance single call. , no calls you'll no overhead def, can define if not use in branches.

with lazy val you'll lazy evaluation: can define if not use in branches, , evaluates once or never, you'll little overhead double check locking on every access lazy val.

as @sargeborsch noted define method, , fastest option:

def even(i: int): boolean = % 2 == 0 

but if need function (not method) function composition or higher order functions (like filter(even)) compiler generate function method every time using function, performance worse val.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -