如何在 Scala 3 中进行类型级添加?

2024-01-03

如何在 Scala 3 中实现类型级操作(在本例中为加法)?

这是我想做的(这不能编译):

case class foo[S <: Int & Singleton](value: Double) {
    def bar[T <: Int & Singleton](that: foo[T]): foo[S + T] = new foo[S + T](this.value * that.value)
}

val t1 = foo[1](1.5)
val t2 = foo[1](2.0)

val t3 = t1 bar t2 //foo[2](3.0)

PS:SIP-23 https://docs.scala-lang.org/sips/42.type.html提案讨论了在 Scala 2 中实现此类行为的库,但我对 Scala 3 感兴趣。


你需要导入scala.compiletime.ops.int.+

https://docs.scala-lang.org/scala3/reference/metaprogramming/compiletime-ops.html#the-scalacompiletimeops-package https://docs.scala-lang.org/scala3/reference/metaprogramming/compiletime-ops.html#the-scalacompiletimeops-package

但是你必须删除上限& Singleton for S

case class foo[S <: Int /*& Singleton*/](value: Double):
  def bar[T <: Int & Singleton](that: foo[T]): foo[S + T] =
    new foo[S + T](this.value * that.value)

问题是+定义为

type +[X <: Int, Y <: Int] <: Int

此加法由编译器在编译时执行,但技术上没有上限<: Singleton for S + T.

如果你真的想恢复上限S您可以用广义类型约束替换上限<:<

case class foo[S <: Int](value: Double)(using S <:< Singleton):
  def bar[T <: Int & Singleton](that: foo[T])(using (S + T) <:< Singleton): foo[S + T] =
    new foo[S + T](this.value * that.value)

更多关于差异的信息<: vs <:< :

在 scala 3 中,是否可以使用协变/逆变类型构造函数来支持强制子类型? https://stackoverflow.com/questions/75762318/in-scala-3-is-it-possible-to-make-covariant-contravariant-type-constructor-to-h

https://blog.bruchez.name/posts/generalized-type-constraints-in-scala/ https://blog.bruchez.name/posts/generalized-type-constraints-in-scala/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Scala 3 中进行类型级添加? 的相关文章

随机推荐