5

为什么不应用以下隐式方法?以及如何在具有隐式范围X的情况下自动将实例转换为实例。YConversion[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
4

1 回答 1

4

使您的转换 extend 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
于 2013-05-02T15:13:20.993 回答