This works
def func(f: => Int) = f
This dosn't (inside class for example)
type EmptyFunct = => Int
or
type EmptyFunct = (=> Int)
Scala version 2.9 Two questions:
- Why dosn't syntax sugar work开发者_StackOverflow in second case?
- How to define this function without syntax sugar?
=> Int is not exactly a function without parameter, it is an Int argument with call by name passing convention. (Of course, that is rather fine a point, as it is implemented by passing a function without parameter ).
The function without argument is written () => Int
. You can do type EmptyFunct = () => Int
.
It is not a type. Inside func, f will be typed as an Int. An argument of type () => Int will not.
def func(f: => Int) = f *2
func (: => Int) Int
But
def func(f: () => Int) : Int = f*2
error: value * is not a member of () => Int
You should use Function0
In the first case it does not work because you declare a non argument Function but because you indicates that the parameter is called by name.
I don't see much sense in a method, returning an int, invoked with no parameter. Either it returns a constant, so you could use the constant, or it would use a var?
So let's go with a var:
var k = 10
val fi = List (() => k * 2, () => k - 2)
val n = fi(0)
n.apply
k = 11
n.apply
result is 20, then 22.
精彩评论