【问题标题】:Typeclass Instance of a Dependent Type依赖类型的类型类实例
【发布时间】:2021-12-10 18:27:36
【问题描述】:

假设我有一个Display[T] { apply(t: T): Unit } 类型类,用于显示实例(我有StringInt 等的实例)。而且我还有一个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


    【解决方案1】:

    你丢失了类型优化

    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}"
    

    【讨论】:

      【解决方案2】:

      您应该使用标准的given ... with 语法:

      given TCWithDependentType[Int] with
        type DependentType = String
      
        def apply(i: Int): String =
          s"${i}"
      

      这样您的代码看起来更干净,并且不会丢失类型信息。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多