Scala 代码:
object Path {
def unapply(s:String):Some[String] = Some(s)
}
val s = "hello world"
val h = "hello"
s match {
case Path(s"$h world") => println("Get hello")
case _ => println("???")
}
我试图在模式匹配中使用s"$var"
,但它无法编译:
<console> error: method s is not a case class, nor does it have
an unapply/unapplySeq member
case Path(s"$h world") => println("Get hello")
为什么scala编译不了?
如果我把它放在 if
子句中:
s match {
case Path(p) if p == s"$h world" => println("Get hello")
case _ => println("???")
}
它运行良好。
为什么scala编译不了?
最佳答案
Why scala can't compile it?
它基本上是一个方法调用(参见 http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.StringContext ),模式中不允许方法调用(并且通常在那里没有意义)。
If I put it in if clause:
It's working well.
因为 if
采用表达式,而不是模式。
你可以做的另一件事:
val A = s"$h world" // note upper-case
s match {
case Path(A) => ...
}
关于scala - 为什么 Scala 模式匹配不支持 `s"$var"`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24604877/