scala - 为什么 Scala 模式匹配不支持 `s"$var"`?

标签 scala pattern-matching

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/

相关文章:

Scala 柯里化(Currying)和类型推断

linux - 如何从 Scala 执行内置的 shell

exception - OCaml,了解错误消息

javascript - 正则表达式和javascript,一些匹配消失了!

javascript - 匹配 : - 内文本的正则表达式

scala - 在 Apache Spark 中使用分类和数值特征对数据进行聚类

scala - 如何在 Scala 中收集 map 列表中的项目

scala - 增加 Scala 的 JVM 堆大小?

python - 将字符串分解为已知模式

rust - 是否可以在模式中创建可变引用的可变值?