开发者

Why does List(_*) fail to match List(4,18,52) in Scala match expression?

开发者 https://www.devze.com 2023-01-31 14:49 出处:网络
I\'m working thro开发者_如何学编程ugh the O\'Reilly Programming Scala book, and have run into a stumbling block with this code sample:

I'm working thro开发者_如何学编程ugh the O'Reilly Programming Scala book, and have run into a stumbling block with this code sample:

/* 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!" );
}
}     

According to the text, the List( _* ) should match any List with zero or more elements, but when I execute this, the List(4,18,52) does not match, and falls into the case _ section (or, if that's removed, throws a MatchError).

Any idea why this isn't matching? Has there been a language change since the book was published, or do I just have one of those "typos that you can't see yourself" things going on?


What version of Scala do you use?

In Scala 2.8.1.final, it will complain the last case is unreachable.

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> 

And it works fine to match the empty list.

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> 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号