How to define scala type for no argument function?
Asked Answered
S

3

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?
Sorption answered 29/8, 2011 at 10:19 Comment(1)
Can you give an example of the usage of EmptyFunct that shows why () => Unit doesn't fit your need?Annecy
N
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

Nianiabi answered 29/8, 2011 at 10:36 Comment(4)
So there are no way to create collection of no arg (: =>Unit) functions?Sorption
See my response: Collection[Function0[Unit]]Annecy
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.Nianiabi
To define a collection: val c: List[()=>Unit] = List( () => println("hello"), () => println("world") ).Humism
A
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.

Annecy answered 29/8, 2011 at 10:35 Comment(1)
This is not solution to my problem. Because Function0 is actually has type () => T not (=> T) which as I undertand not function at all.Sorption
M
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.

Mariettamariette answered 29/8, 2011 at 13:2 Comment(2)
"I don't see much sense in a method, returning an int, invoked with no parameter." A counter ?Annecy
Or any callback function which has all its context in creation phaseSorption

© 2022 - 2024 — McMap. All rights reserved.