【发布时间】:2016-04-17 21:16:20
【问题描述】:
我可能遇到过一个版本的链式隐式转换问题 (http://docs.scala-lang.org/tutorials/FAQ/chaining-implicits.html)。而且我不知道如何解决它。
我在下面附上了一个SSCCE 示例来说明这个问题。让我在这里添加一些细节:
1) 我想要一个类似下面的方法:
def chainedTransform[A, B, C](a: A)(f1: F[A, B], f2: F[B, C]): C
它应该将值从类型A 转换为类型C。
2) 具有必要类型参数的转换器F 可能不存在于范围内,但令人满意的隐式转换存在。
3) 整个方法在下面的 sn-p 中演示。
test("Mutliple conversions") {
val f1: Function1[String, Int] = (s) => s.toInt
val f2: Function1[Int, Boolean] = (i) => i > 0
val f3: Function[Option[Int], Option[Boolean]] = (iOpt) => iOpt map (_ > 0)
implicit def toOptFun[A, B](f: Function1[A, B]): Function1[Option[A], Option[B]] =
new Function1[Option[A], Option[B]] {
override def apply(v1: Option[A]): Option[B] = v1 map f
}
case class Test[A](param: A) {
def transform[B](t1: Function1[A, B]): B = t1(param)
def chainedTransform[B, C](t1: Function1[A, B], t2: Function1[B, C]): C = t2(t1(param))
}
val test1 = Test("123")
assert(test1.chainedTransform(f1, f2))
val test2 = Test(Option("123"))
//toOptFun implicit conversion is applied successfully
assert(test2.transform(f1) == Some(123))
//Does not compile:
//test2.chainedTransform(f1, f2)
// [error] found : Int => Boolean
// [error] required: Option[Int] => Boolean
// [error] test2.chainedTransform(f1, f2)
// [error] ^
//f3 is exactly what toOptFun(f2) would produce if applied
assert(test2.chainedTransform(f1, f3) == Some(true))
}
任何想法如何使它工作?
【问题讨论】: