我正在阅读O' Reilly Programming Scala 一书,并且使用此代码示例遇到了绊脚石:
/* matching on sequences */
val willWork = List(1, 3, 23, 90 );
val willNotWork = List( 4, 18, 52 );
val empty = List();
for( l <- List(willWork, willNotWork, empty ))
{
l match
{
case List( _, 3, _, _ ) => println( "Four elements, with the second being '3'." );
case List( _* ) => println( "Any other list with zero or more elements" );
case _ => println( "Uh, oh!" );
}
}
根据文本,List(_ *)应该匹配任何具有零个或多个元素的List,但是当我执行它时,List(4,18,52)不匹配,并且属于case _ section (或者,如果删除了它,则抛出MatchError)。
知道为什么这不匹配?自本书出版以来,语言是否发生过变化,或者我是否只有其中一个“你自己无法看到自己”的错别字。事情还在继续?
答案 0 :(得分:3)
您使用的是什么版本的Scala?
在Scala 2.8.1.final中,它会抱怨最后case
无法访问。
scala> val willWork = List(1, 3, 23, 90 );
willWork: List[Int] = List(1, 3, 23, 90)
scala> val willNotWork = List( 4, 18, 52 );
willNotWork: List[Int] = List(4, 18, 52)
scala> val empty = List();
empty: List[Nothing] = List()
scala>
scala> for( l <- List(willWork, willNotWork, empty ))
| {
| l match
| {
| case List( _, 3, _, _ ) => println( "Four elements, with the second being '3'." );
| case List( _* ) => println( "Any other list with zero or more elements" );
| case _ => println( "Uh, oh!" );
| }
| }
<console>:15: error: unreachable code
case _ => println( "Uh, oh!" );
^
scala>
它可以很好地匹配空列表。
scala> val willWork = List(1, 3, 23, 90 );
willWork: List[Int] = List(1, 3, 23, 90)
scala> val willNotWork = List( 4, 18, 52 );
willNotWork: List[Int] = List(4, 18, 52)
scala> val empty = List();
empty: List[Nothing] = List()
scala>
scala> for( l <- List(willWork, willNotWork, empty ))
| {
| l match
| {
| case List( _, 3, _, _ ) => println( "Four elements, with the second being '3'." );
| case List( _* ) => println( "Any other list with zero or more elements" );
| }
| }
Four elements, with the second being '3'.
Any other list with zero or more elements
Any other list with zero or more elements
scala>