user1553248
user1553248

Reputation: 1204

scala referencing value of a parameter

If I have the following type and function:

object M {
    type X[Boolean] = Int => Boolean

    def retrieveVal(x: X[Boolean]) : Boolean = //retrieve the Boolean value of x
}

How would I go about retrieving and returning the boolean value?

Upvotes: 1

Views: 51

Answers (1)

Randall Schulz
Randall Schulz

Reputation: 26486

That is a peculiar type alias. It has a formal type parameter (the name of which is irrelevant and hence the choice of Boolean is misleading) that defines a function from Int to that arbitrary type. You then define a method, retrieveVal that takes a particular kind of X that happens to be X[Boolean] (here Boolean is an actual type parameter and hence is the Boolean we're familiar with) and returns some Boolean. However, the function x passed as an argument requires an Int argument and there is none in evidence.

So, if your retrieveVal were defined like this instead:

def retrieveVal(i: Int, x: X[Boolean]): Boolean = ...

you could define it like this:

def retrieveVal(i: Int, x: X[Boolean]): Boolean = x(i)

To wit:

scala> type X[Boolean] = Int => Boolean
defined type alias X

scala> def retrieveVal(i: Int, x: X[Boolean]): Boolean = x(i)
retrieveVal: (i: Int, x: Int => Boolean)Boolean

scala> retrieveVal(23, i => i % 2 == 0)
res0: Boolean = false

Upvotes: 4

Related Questions