假设我有一个用来显示实例的Display[T] { apply(t: T): Unit }类型类(我有String、Int等的实例)。我还有一个将T转换成TCWithDependentType#DependentType的TCWithDependentType[T] { type DependentType ; def apply(t: T): 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)你知道为了让这玩意儿工作我错过了什么吗?
谢谢!艾德里安。
发布于 2021-10-25 09:25:13
您丢失了类型优化
given (TCWithDependentType[Int] {type DependentType = String}) =
new TCWithDependentType[Int]:
type DependentType = String
def apply(i: Int): String = s"${i}"
given (TCWithDependentType[String] {type DependentType = String}) =
new TCWithDependentType[String]:
type DependentType = String
def apply(i: String): String = s"${i}"发布于 2021-10-25 09:58:25
您应该使用标准的given ... with语法:
given TCWithDependentType[Int] with
type DependentType = String
def apply(i: Int): String =
s"${i}"这样,您的代码看起来更整洁,类型信息也不会丢失。
https://stackoverflow.com/questions/69705186
复制相似问题