Does the Scala library provide any support for lifting a method of a given type to a function value?
For example, suppose I want to lift String.length
. I can write
val f: String => Int = _.length
or
val f = { s: String => s.length }
However, this syntax is not always ideal (particularly in the midst of a larger expression). I think I'm looking for something that will enable expressions like
Lift[String](_.length)
Lift[Option[Int]].lift(_.filter)
and I have in mind something like this:
class Lift[T] {
def apply[R](f: T => R): T => R = f
def lift[A, R](f: (T) => (A) => R): (T, A) => R =
f(_)(_)
def lift[A1, A2, R](f: (T) => (A1, A2) => R): (T, A1, A2) => R =
f(_)(_,_)
// ... etc. ...
}
object Lift {
def apply[T] = new Lift[T]
}
Question 1: Does the standard library (or any library) provide something like this?
Question 2: If not, is it possible to write it in such a way that Option.filter
can be lifted as above (rather than as Lift[Option[Int]].lift[Int => Boolean, Option[Int]](_.filter)
)? Without supplying the type parameters on the lift
method I get the following error:
error: missing parameter type for expanded function ((x$1) => x$1.filter) Lift[Option[Int]].lift(_.filter) ^
Update:
Apparently, the problem I'm running in to has something to do with the overloaded lift
method. If I rename the overloads, I can lift Option.filter
without all the extra type parameters.