Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Defining a function to be the correct type

Tags:

scala

I've been playing around with Scala code and have come up against a compiler error which I don't understand. The code generates a vector of pairs of Ints and then tries to filter it.

val L = for (x <- (1 to 5)) yield (x, x * x) 
val f = (x: Int, y: Int) => x > 3
println(L.filter(f))

The compiler complains about trying to use f as an argument for the filter method with the compiler error message being:

error: type mismatch;
found   : (Int, Int) => Boolean
required: ((Int, Int)) => Boolean

How do I define the function f correctly to satisfy the required function type? I tried to add extra parentheses around (x: Int, y: Int) but this gave:

error: not a legal formal parameter
   val f = ((x: Int, y: Int)) => x > 3
            ^
like image 561
Mark Silberbauer Avatar asked Nov 15 '11 14:11

Mark Silberbauer


1 Answers

f has type Function2[Int, Int, Boolean]. L's type is IndexedSeq[Tuple2[Int, Int]] and so filter expects a function of type Function1[Tuple2[Int, Int], Boolean]. Every FunctionN[A, B, .., R] trait has a method tupled, which returns a function of type Function1[TupleN[A, B, ..], R]. You can use it here to transform f to the type expected by L.filter.

println(L.filter(f.tupled))
> Vector((4,16), (5,25))

Alternatively you can redefine f to be a Function1[Tuple2[Int, Int], Boolean] as follows and use it directly.

val f = (t: (Int, Int)) => t._1 > 3
println(L.filter(f))
> Vector((4,16), (5,25))
like image 182
missingfaktor Avatar answered Nov 09 '22 12:11

missingfaktor