Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define scala type for no argument function?

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?
like image 406
yura Avatar asked Aug 29 '11 10:08

yura


People also ask

How does Scala determine types when they are not specified?

For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type. Non-value types are expressed indirectly in Scala.

What is a function with no arguments called?

A nullary or niladic function.

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .


1 Answers

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

like image 176
Didier Dupont Avatar answered Nov 12 '22 01:11

Didier Dupont