8

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:

  1. Why dosn't syntax sugar work in second case?
  2. How to define this function without syntax sugar?
1
  • Can you give an example of the usage of EmptyFunct that shows why () => Unit doesn't fit your need? Commented Aug 29, 2011 at 13:46

3 Answers 3

13

=> 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

Sign up to request clarification or add additional context in comments.

4 Comments

So there are no way to create collection of no arg (: =>Unit) functions?
See my response: Collection[Function0[Unit]]
If you were looking for (: => Unit *) repeated arguments, it is not allowed. Indeed, that could only be Seq[Unit] (Seq contains values, not arguments calling conventions). And be quite useless. What you want is Seq[Function0[Unit]] (or Seq[() => Unit], it means the same thing). Notation will be less convenient : () => x += 1 instead of x+= 1.
To define a collection: val c: List[()=>Unit] = List( () => println("hello"), () => println("world") ).
3

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.

1 Comment

This is not solution to my problem. Because Function0 is actually has type () => T not (=> T) which as I undertand not function at all.
0

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.

2 Comments

"I don't see much sense in a method, returning an int, invoked with no parameter." A counter ?
Or any callback function which has all its context in creation phase

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.