首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >依赖类型的Typeclass实例

依赖类型的Typeclass实例
EN

Stack Overflow用户
提问于 2021-10-25 08:53:04
回答 2查看 60关注 0票数 0

假设我有一个用来显示实例的Display[T] { apply(t: T): Unit }类型类(我有StringInt等的实例)。我还有一个将T转换成TCWithDependentType#DependentTypeTCWithDependentType[T] { type DependentType ; def apply(t: T): DependentType }

我正在尝试显示DependentType的实例,但它无法工作,因为编译器找不到Display[TCWithDependentType#DependentType] (我假设它就是这个)实例(即使它在编译时应该是已知的)。

下面是完整的示例(相关的Scastie在这里:https://scastie.scala-lang.org/RXmC776DQeywLOxj2xbHQg):

代码语言:javascript
复制
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)

你知道为了让这玩意儿工作我错过了什么吗?

谢谢!艾德里安。

EN

回答 2

Stack Overflow用户

发布于 2021-10-25 09:25:13

您丢失了类型优化

代码语言:javascript
复制
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}"
票数 3
EN

Stack Overflow用户

发布于 2021-10-25 09:58:25

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

代码语言:javascript
复制
given TCWithDependentType[Int] with
  type DependentType = String

  def apply(i: Int): String =
    s"${i}"

这样,您的代码看起来更整洁,类型信息也不会丢失。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69705186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档