Why scala pattern matching doesn't support `s"$var"`?
pattern-matching, scala
Solution
Why scala can't compile it?
It's basically a method call (see http://www.scala-lang.org/files/archive/nightly/docs/library/index.html#scala.StringContext), and method calls aren't allowed in patterns (and don't generally make sense there).
If I put it in if clause:
It's working well.
Because `if` takes an expression, not a pattern.
Another thing you could do:
val A = s"$h world" // note upper-case
s match {
case Path(A) => ...
}
Problem
Scala code: ``` 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("???") } ``` I tried to use `s"$var"` in pattern matching, but it can't compiled: ``` <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") ``` Why scala can't compile it? If I put it in `if` clause: ``` s match { case Path(p) if p == s"$h world" => println("Get hello") case _ => println("???") } ``` It's working well. Why scala can't compile it?