스칼라 문서에 by name parameter라는 게 있다. 문법적인 의미라서 크게 와닿지는 않는다. 문법 정도만.. 



4.6.1 By-Name Parameters 


Syntax: ParamType ::= ‘=>’ Type The type of a value parameter may be prefixed by =>, e.g. x: => T . 


The type of such a parameter is then the parameterless method type => T . This indicates that However, at present singleton types of method parameters may only appear in the method body; so dependent method types are not supported. Basic Declarations and Definitions the corresponding argument is not evaluated at the point of function application, but instead is evaluated at each use within the function. 


That is, the argument is evaluated using call-by-name. The by-name modifier is disallowed for parameters of classes that carry a val or var prefix, including parameters of case classes for which a val prefix is implicitly generated.


The by-name modifier is also disallowed for implicit parameters (§7.2). Example 4.6.2 The declaration def whileLoop (cond: => Boolean) (stat: => Unit): Unit indicates that both parameters of whileLoop are evaluated using call-by-name.






by-name parameter는 함수를 매개변수로 보내고 해당 함수를 lazy evaluation을 할 수 있는 기법이다. 


더 쉽게 말하면 매개변수의 계산을 지연하고 싶어할 때 사용할 수 있다 .





아래 웹 페이지가 이해하는 데 많은 도움이 되었다.


https://groups.google.com/forum/#!topic/scala-korea/qyjq7IEdwRc

http://daily-scala.blogspot.kr/2009/12/by-name-parameter-to-function.html



def takesFunction(functionByName: () => Int) = println(functionByName())
takesFunction(() => 10)

by-name 매개변수는 :() => 형태를 가지고 있고, 결과는 10이다. 그리고 :() => 매개변수를 :=>으로 변경할 수 있고, 사용할 때는 깔끔하게 리턴 값만 넣을 수 있다.



def takesFunction(functionByName: => Int) = println(functionByName)
takesFunction(10)



래핑한 send 함수를 이용한다.


def takesFunction(functionByName: () => Int) = println(functionByName())
def send(x: => Int) = takesFunction(() => x)
send{10}


래핑한 send 함수를 사용해서 결과를 만들 수 있다. 

def takesAnotherFunction1(functionByName: => Int) = println(functionByName)
def sendAnother1(x: => Int) = takesAnotherFunction1(x)
sendAnother1{10}


다른 형태로도 사용할 수 있다. 


def takesAnotherFunction1(functionByName: => Int) 
                               = println(functionByName)
def sendAnother1(x: => Int) = takesAnotherFunction1(x)
sendAnother1{10}

def takesAnotherFunction2(functionByName: => Int) = println(functionByName)
def sendAnother2(x: => Int) = takesAnotherFunction2(x)
sendAnother2{10}



Posted by '김용환'
,