Wednesday, December 16, 2009
By-name-parameter to Function
Today's topic is related to Defining Custom Control Structures. By name parameters are not function objects in the same way as other functions. Normally you need to invoke a function:
Compare that to a by-name-parameter function:
So the issue is how can you pass a by-name-parameter to a method that takes a function as a parameter without having to do:
the alternative syntax is:
- scala> def exec(func: () => Int) = func()
- exec: (() => Int)Int
- // exec invokes the function so 10 is the result
- scala> exec (() => 10)
- res1: Int = 10
- scala> def exec(func: () => Int) = func
- exec: (() => Int)() => Int
- // here exec returns the function:
- scala> exec (() => 10)
- res2: () => Int = <function>
Compare that to a by-name-parameter function:
- scala> def exec(func: => Int) = func
- exec: (=> Int)Int
- // by-name-parameters are executed when they are referenced
- // so the result is 10
- scala> exec {10}
- res3: Int = 10
- // This is not legal because by-name-parameters
- // are not normal functions
- scala> def exec(func: => Int) = func()
- <console>:4: error: func of type Int does not take parameters
- def exec(func: => Int) = func()
So the issue is how can you pass a by-name-parameter to a method that takes a function as a parameter without having to do:
- scala> def takesFunc(func: () => Int) = println(func())
- takesFunc: (() => Int)Unit
- scala> def send(x: => Int) = takesFunc(() => x)
- send: (=> Int)Unit
- scala> send{2}
- 2
the alternative syntax is:
- scala> def send(x: => Int) = takesFunc (x _)
- send: (=> Int)Unit
- scala> send {2}
- 2
posted
12/16/2009
Labels:
by-name-parameter,
control structure,
function,
Scala
Subscribe to:
Post Comments (Atom)
3 comments:
Exactly what I was looking for - thanks!
Reply DeleteDito! Great blog!
Reply DeleteI think your posts are great, but the color scheme does not agree with me. Maybe you could try to use other code formatting/coloring tools that will improve readability.
Reply DeleteThanks and keep up the great work!