在 scala 3 中,使用内联匹配时,如何确保两个类型参数相同。
class Div[A,B]
transparent inline def simplify [A](a: QuantityUnit[A]) =
inline a match {
// only match if a and b are the same
case _: Div[a,b] /* a =:= b */ => "string"
case _ => 24
}
// should produce 24 because the type params are different
val a: String = simplify(new Div[Boolean,Int])
// should produce "string" because the type params are the same
val b: Int = simplify(new Div[Boolean,Boolean])
这是关键行,我想表达的是注释掉的内容:
case _: Div[a,b] /* a =:= b */ => "string"
我想出的最好的办法是这样的:
case _: Div[a,b] => inline erasedValue[b] match {
case _: a => "string"
case _ => ...
}
但它迫使我突破主要的比赛语句。
最佳答案
我偶然发现了一些似乎有效的东西。最简单的版本:
// type alias
type SameParamDiv[A] = Div[A,A]
...
case _: SameParamDiv[a] => "string"
我尝试内联同样的事情:
case _ : (([a] =>> Div[a,a])[_]) => {
我不太确定语法,但它似乎有效:D
为了完整起见,这里有一些不起作用的东西:
// never matches
case _ : Div[a,b] if erasedValue[a] == erasedValue[b] =>
关于scala - 如何确保内联类型匹配(scala 3)中的两个参数引用相同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67680285/