gpt4 book ai didi

scala - 隐式转换不起作用

转载 作者:行者123 更新时间:2023-12-02 06:14:22 26 4
gpt4 key购买 nike

为什么不应用以下隐式方法?如何实现自动将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com