我正在探索 scala3 内联的可能性。我制作了一个简单的示例,我希望在编译时应用构造密封类的验证方法:
import scala.compiletime.{ error, codeOf }
sealed abstract class OneOrTwo(val code: String)
object OneOrTwo {
case object One extends OneOrTwo("one")
case object Two extends OneOrTwo("two")
def from(s: String): Option[OneOrTwo] =
s match {
case One.code => Some(One)
case Two.code => Some(Two)
case _ => None
}
inline def inlinedFrom1(s: String): OneOrTwo = {
inline s match {
case "one" => One
case "two" => Two
case _ => error("can't make a OneOrTwo out of " + codeOf(s))
}
}
val test1 = OneOrTwo.inlinedFrom1("one") // compiles
val test12 = OneOrTwo.inlinedFrom1("three") // doesn't compile as expected -> can't make a OneOrTwo out of "three"
}
到现在为止还挺好。但我真正想要的是能够重用from
内联函数中的函数。这是我尝试:
// this goes in the OneOrTwo companion object as well
inline def inlinedFrom2(s: String): OneOrTwo = {
from(s).getOrElse(error("can't make a OneOrTwo out of " + codeOf(s)))
}
inline def inlinedFrom3(s: String): OneOrTwo = {
s match {
case One.code => One
case Two.code => Two
case _ => error("can't make a OneOrTwo out of " + codeOf(s))
}
}
val test2 = OneOrTwo.inlinedFrom2("one") // doesn't compile -> can't make a OneOrTwo out of "one"
val test3 = OneOrTwo.inlinedFrom3("one") // doesn't compile -> can't make a OneOrTwo out of "one"
inlinedFrom3
是一种概括,表明如果我直接匹配对象的代码,编译器不会看到它们与输入字符串相同并采用错误的分支。
我想了解的是为什么inlinedFrom3
不起作用以及是否有办法使它起作用。
注意:我使用的是 scala 3.0.0-RC2