比方說,我有一個Display[T] { apply(t: T): Unit }這是為了顯示實體使用型別類(和我有實體String,Int等等)。我也有一個TCWithDependentType[T] { type DependentType ; def apply(t: T): DependentType }which 轉換T為TCWithDependentType#DependentType.
我正在嘗試顯示 a 的實體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)
你知道我缺少什么才能使這件事起作用嗎?
謝謝!阿德里安。
uj5u.com熱心網友回復:
你失去了型別改進
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}"
uj5u.com熱心網友回復:
您應該使用標準given ... with語法:
given TCWithDependentType[Int] with
type DependentType = String
def apply(i: Int): String =
s"${i}"
這樣你的代碼看起來更干凈,不會丟失任何型別資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338806.html
