简体   繁体   English

Scala 2.12:无法在提取器对象中使用取消应用

[英]Scala 2.12: Unable to use unapply in extractor object

I am following through Scala Tour provided on docs.scala-lang.org . 我将遵循docs.scala-lang.org上提供的Scala Tour。 I am stuck at the extractor objects tutorial: https://docs.scala-lang.org/tour/extractor-objects.html 我陷入了提取器对象教程的困境: https//docs.scala-lang.org/tour/extractor-objects.html

Here is the code I am trying to compile: 这是我要编译的代码:

object IdGenerator {
  private val id: AtomicInteger = new AtomicInteger
  def apply(name: String): String = id.incrementAndGet + "--" + name
  def unapply(genID: String): Option[String] = {
    val idParts = genID.split("--")
    if (idParts.head.nonEmpty && idParts.tail.nonEmpty)
      Some(idParts(0))
    else
      None
  }
}

println(IdGenerator("ABC"))
println(IdGenerator("DEF"))
println(IdGenerator("XYZ"))

IdGenerator(idName) = IdGenerator("ABC")
println(idName)
println(IdGenerator.unapply(IdGenerator("ABC")))

Here is the error: 这是错误:

D:\MyApps\ScalaPrac\helloworld\hello\src\main\scala\example\Hello.scala:68:5: value update is not a member of object example.IdGenerator
IdGenerator(idName) = IdGenerator("ABC")

It says that value update is not a member of object . 它说值更新不是object的成员 Sure, it isn't. 当然可以。 But I am not asking it to look for update method, I want it to look for unapply instead. 但我不问它来寻找update的方法,我希望它看起来对unapply来代替。

IdGenerator(idName) = x looks like an assignment, but it actually is syntax sugar for IdGenerator.update(idName, x) . IdGenerator(idName) = x看起来像一个赋值,但实际上是IdGenerator.update(idName, x)语法糖。 That explains the error message you get. 这说明了您收到的错误消息。

You need to use the val keyword to extract idName : 您需要使用val关键字来提取idName

val IdGenerator(idName) = IdGenerator("ABC")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM