Scala @ operator

后端 未结 5 1660
别那么骄傲
别那么骄傲 2020-11-27 09:32

What does Scala\'s @ operator do?

For example, in the blog post Formal Language Processing in Scala, Part 2 there is a something like this

c         


        
5条回答
  •  执念已碎
    2020-11-27 10:13

    It enables one to bind a matched pattern to a variable. Consider the following, for instance:

    val o: Option[Int] = Some(2)
    

    You can easily extract the content:

    o match {
      case Some(x) => println(x)
      case None =>
    }
    

    But what if you wanted not the content of Some, but the option itself? That would be accomplished with this:

    o match {
      case x @ Some(_) => println(x)
      case None =>
    }
    

    Note that @ can be used at any level, not just at the top level of the matching.

提交回复
热议问题