Reputation: 39
I have a problem. I'm representing a set by its characterisitc function, so I've defined a type alias for this representation. The function filterHead should take a set and a predicate as an input and return a result of function f .
type Set = Int => Boolean
def filterHead(s: Set, f: Int => Boolean): Boolean = f(s.head)
Then the following error occures: "value head is not a member of Int => Boolean". And the error related to type allias definition, not to input function f
Upvotes: 0
Views: 168
Reputation: 14318
When you define the alias for Set
, the Set
parameter will be 'unrolled' to the full type:
scala> type Set = Int => Boolean
defined type alias Set
scala> def foo(s : Set, i : Int) = ???
foo: (s: Int => Boolean, i: Int)Nothing
And when you're using the Set(1,2,3)
, you're using the companion object's apply
method which returns a different type:
scala> val set = Set(4,1,2)
set: scala.collection.immutable.Set[Int] = Set(4, 1, 2)
Also, as you might notice, the collection set is generic here. You could make a generic type alias too though (the alias would be Set[T]
), so there still could be some confusion.
Solution? Use a full type name:
scala> def filterHead(s : scala.collection.immutable.Set[Int], setFunc : Set) = setFunc(s.head)
filterHead: (s: scala.collection.immutable.Set[Int], setFunc: Int => Boolean)Boolean
Or give your alias a different name:
type SetFunc = Int => Boolean
or, in a generic way:
type SetFunc[T] = T => Boolean
Or even import the scala.collection.immutable.Set[T]
under a different name - alias on import.
Upvotes: 1