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'
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
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 _
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With