你需要导入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/