为什么编译器不推断依赖类型?
Why isn't dependent type inffered by the compiler?
我正在学习 shapeless 并且遇到了一些关于依赖类型的误解。这是示例:
object App {
trait Converter[A]{
type Output
def convert(a: A): Output
}
implicit def toStringConverter[A]: Converter[A] = new Converter[A] {
override type Output = String
override def convert(a: A): String = s"Converted value = ${a.toString}"
}
def getConvertedValue[A](a: A)(implicit converter: Converter[A]) = converter.convert(a)
def main(args : Array[String]) {
val someValue: String = getConvertedValue(new Object) //compiler error, type mismatch
val someValue2 = getConvertedValue(new Object) //fine
println(someValue2) //prints the expected value
}
}
我不明白第一种情况的编译错误。编译器正确地找到了 implicit def toStringConverter[A]
的隐含值 override type Output = String
。因此它具有推断 return 类型 String
.
的所有信息
为什么编译不通过?有没有办法让它在不参数化输出类型的情况下将 return 类型推断为 String
?
您可以通过为 toStringConverter
指定更精确的 return 类型来实现:
implicit def toStringConverter[A]: Converter[A] { type Output = String } = new Converter[A] { ... }
或者根本不指定它以便推断出上述类型,但不建议将其用于隐式。
Compiler correctly finds the implicit value of implicit def toStringConverter[A] which has override type Output = String. So it has all the information to infer return type String.
它不能依赖于 toStringConverter[A]
的 实现 ,只能依赖于它的类型。
我正在学习 shapeless 并且遇到了一些关于依赖类型的误解。这是示例:
object App {
trait Converter[A]{
type Output
def convert(a: A): Output
}
implicit def toStringConverter[A]: Converter[A] = new Converter[A] {
override type Output = String
override def convert(a: A): String = s"Converted value = ${a.toString}"
}
def getConvertedValue[A](a: A)(implicit converter: Converter[A]) = converter.convert(a)
def main(args : Array[String]) {
val someValue: String = getConvertedValue(new Object) //compiler error, type mismatch
val someValue2 = getConvertedValue(new Object) //fine
println(someValue2) //prints the expected value
}
}
我不明白第一种情况的编译错误。编译器正确地找到了 implicit def toStringConverter[A]
的隐含值 override type Output = String
。因此它具有推断 return 类型 String
.
为什么编译不通过?有没有办法让它在不参数化输出类型的情况下将 return 类型推断为 String
?
您可以通过为 toStringConverter
指定更精确的 return 类型来实现:
implicit def toStringConverter[A]: Converter[A] { type Output = String } = new Converter[A] { ... }
或者根本不指定它以便推断出上述类型,但不建议将其用于隐式。
Compiler correctly finds the implicit value of implicit def toStringConverter[A] which has override type Output = String. So it has all the information to infer return type String.
它不能依赖于 toStringConverter[A]
的 实现 ,只能依赖于它的类型。