function - why declaration of methods in different style different results in scala -


below 2 methods declared in different style. both doing same work. wondering, why

  1. different syntax required check type of function (yellow block)
  2. different syntax required call function (green block)
  3. declaration of both methods on scala repl gives different results (red block)

also, please suggest, 1 preferred way declare methods or there special use cases both styles of method declaration?

enter image description here


edit 1:

below commands screenshot :-

welcome scala version 2.11.7 (java hotspot(tm) 64-bit server vm, java 1.7.0_79). type in expressions have them evaluated. type :help more information.  scala> def add(x:int, y :int): int = {x+y} add: (x: int, y: int)int  scala> def sum = (x:int, y:int) => {x+y} sum: (int, int) => int  scala> :t add <console>:12: error: missing arguments method add; follow method `_' if want treat partially applied function        add        ^  scala> :t add(_, _) (int, int) => int  scala> :t sum (int, int) => int  scala> add <console>:12: error: missing arguments method add; follow method `_' if want treat partially applied function        add        ^  scala> add(_, _) res1: (int, int) => int = <function2>  scala> sum res2: (int, int) => int = <function2> 

edit 2:

@shadowlands

i have read on dzone, states "when function expected method provided, automatically converted function. called eta expansion.".

now, if eta takes care convert methods function. required use sum style, because looks additional overhead of function<> object.

simply put, add function takes 2 int arguments , returns int result, while sum 0-argument function returns new function that, in turn, takes 2 int arguments , returns int result. indeed, sum readily defined as:

def sum = add _ 

as way define functions, depends on how used. generally, use add style of time, easier understand , work with. if, however, passing function argument function, sum-style formulation can more convenient , may convey more of intent on how function expected used.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -