Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meant by 'MyType = Int => Boolean'

Tags:

scala

What is meant by below scala declaration :

type MyType = Int => Boolean

Here is my understanding :

I'm declaring a new type 'MyType' but what is meant by the higher order function 'Int => Boolean'

like image 831
user701254 Avatar asked Sep 28 '12 09:09

user701254


2 Answers

It's not so much declaring a new type as declaring a new type alias. They're still the same type: but the alias lets your write it a little more succinctly.

Int => Boolean is the type of a function that takes one argument, an Int, and returns a Boolean.

For example, a function like "greater than 5" could have type Int => Boolean:

type MyType = Int => Boolean
val greaterThan5: MyType = (x: Int) => x > 5
greaterThan5(7)  // true
like image 181
dhg Avatar answered Nov 11 '22 18:11

dhg


You are correct, the following compiles:

type MyType = Int => Boolean
def positive(x: Int) = x > 0
val fun: MyType = positive
fun(42)  //yields true

Here you declare type alias saying that MyType equivalent to a function taking Int and returning Boolean. Then you create a method matching such declaration. Finally you assign this method to a variable of MyType type. It compiles and works just fine.

Note that this is just an alias, not a new type:

trait MyType2 extends (Int => Boolean)
val fun2: MyType2 = positive _
error: type mismatch;
 found   : Int => Boolean
 required: MyType2
       val fun2: MyType2 = positive _
                           ^
like image 40
Tomasz Nurkiewicz Avatar answered Nov 11 '22 20:11

Tomasz Nurkiewicz