为什么不应用以下隐式方法?如何实现自动将 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
最佳答案
让你的转换扩展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
关于scala - 隐式转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16341256/