给予:
$cat build.sbt
scalaVersion := "2.11.8"
libraryDependencies += "org.scala-lang.modules" %% "scala-xml" % "1.0.6"然后,
$sbt console
def exactlyOne[A](xs: Seq[A]): Option[A] = xs match {
case head :: Nil => Some(head)
case _ => None
}
scala> val xml = <root><a/></root>
xml: scala.xml.Elem = <root><a/></root>
scala> xml \ "a"
res3: scala.xml.NodeSeq = NodeSeq(<a/>)
scala> exactlyOne( res3 )
res4: Option[scala.xml.Node] = None显然,没有使用Seq#unapply:
scala> exactlyOne( Seq(1) )
res2: Option[Int] = Some(1)我的理解是,unapply将被调用,通常在类的companion object上。
(我找到了Node#unapplySeq Node#unapplySeq scala.xml.MetaData,Seqscala.xml.Node)),但我不确定这是否被调用了。
这里是在match上调用哪一种方法?
发布于 2016-12-02 21:00:22
NodeSeq不是List,所以尝试将其模式匹配为一个将失败的模式。如果您想要使用某种类型的unapplySeq来匹配它,则需要这样做:
def exactlyOne[A](xs: Seq[A]): Option[A] = xs match {
case Seq(head) => Some(head)
case _ => None
}
scala> exactlyOne(<root>hello</root>)
res5: Option[scala.xml.Node] = Some(<root>hello</root>)
scala> exactlyOne(<root>hello</root><foo>world</foo>)
res6: Option[scala.xml.Node] = Nonehttps://stackoverflow.com/questions/40940528
复制相似问题