隐式转换不起作用

时间:2013-05-02 14:54:55

标签: scala implicit-conversion

为什么不应用以下隐式方法?如何在范围内具有隐式X的情况下自动将Y的实例转换为Conversion[X,Y]的实例。

trait Conversion[X, Y] {
  def apply(x: X): Y
}
implicit object Str2IntConversion extends Conversion[String, Int] {
  def apply(s: String): Int = s.size
}
implicit def convert[X, Y](x: X)(implicit c: Conversion[X, Y]): Y = c(x)

val s = "Hello"
val i1: Int = convert(s)
val i2: Int = s // type mismatch; found: String  required: Int

1 个答案:

答案 0 :(得分:4)

让您的转化延伸Function1,然后您不再需要辅助方法:

trait Conversion[X, Y] extends (X => Y) {
  def apply(x: X): Y
}

// unchanged
implicit object Str2IntConversion extends Conversion[String, Int] {
  def apply(s: String): Int = s.size
}

// removed convert

// unchanged
val s = "Hello"
val i1: Int = convert(s)
val i2: Int = s