【发布时间】:2021-12-10 18:27:36
【问题描述】:
假设我有一个Display[T] { apply(t: T): Unit } 类型类,用于显示实例(我有String、Int 等的实例)。而且我还有一个TCWithDependentType[T] { type DependentType ; def apply(t: T): DependentType },它将T 转换为TCWithDependentType#DependentType。
我正在尝试显示DependentType 的实例,但它不起作用,因为编译器无法找到Display[TCWithDependentType#DependentType](我假设是这个)实例(即使它应该是在编译时已知)。
这里是完整的例子(相关的 Scastie 在这里:https://scastie.scala-lang.org/RXmC776DQeywLOxj2xbHQg):
trait TCWithDependentType[T]:
type DependentType
def apply(t: T): DependentType
def dependentTypeOf[T](t: T)(using
tcWithDependentType: TCWithDependentType[T]
): tcWithDependentType.DependentType =
tcWithDependentType(t)
given TCWithDependentType[Int] =
new TCWithDependentType[Int]:
type DependentType = String
def apply(i: Int): String =
s"${i}"
given TCWithDependentType[String] =
new TCWithDependentType[String]:
type DependentType = String
def apply(i: String): String =
s"${i}"
trait Display[T]:
def apply(t: T): Unit
def display[T](t: T)(using displayForT: Display[T]): Unit =
displayForT(t)
/* given [T]: Display[T] =
new Display[T]:
def apply(t: T): Unit =
println(s"I display \"${t}\" which is unknown") */
given Display[String] =
new Display[String]:
def apply(t: String): Unit =
println(s"I display \"${t}\" which is a String")
given Display[Int] =
new Display[Int]:
def apply(t: Int): Unit =
println(s"I display \"${t}\" which is a Int")
val dv = dependentTypeOf(1)
display(dv)
你知道我为了让这件事发挥作用而缺少什么吗?
谢谢! 阿德里安。
【问题讨论】:
标签: scala typeclass implicit dependent-type scala-3