Scala: How can I match only the first two elements of an arbitrary List

China☆狼群 提交于 2019-12-10 11:49:00

问题


I'm attempting to match a lists first two elements, however, it wont accept lists of arbitrary length. The below code fails.

  def demoCases() = {
    def actor1 = new Actor[Employee] {}
    def actor2 = new Actor[Employee] {}
    def actor3 = new Actor[Animal] {}

    var actors = List(actor1, actor2, actor3);
    println();
    actors match {
      case (_: Employee) :: (_: Employee) :: tail
        => {println("nice 2  employees to start with ")};

      case Nil
        => {println("no match")}
    }

The exception :

Exception in thread "main" scala.MatchError: List(.....)

How can i specify that only the two elements first of the list need to match this expression?


回答1:


Just replace case Nil by case _ => println("no match"). _ as a pattern means "match anything". But note that your first case requires that the first two elements of the list are Employees, not Actors.




回答2:


The following does not work thanks to type-erasure (pointed out by Alexey Romanov)

case (_: Actor[Employee]) :: (_: Actor[Employee]) :: tail

Therefore I cannot think of any way to do what you want without restructuring the code. For example if you made Employee a member of Actor somehow, and made Actor a case class, you could do

case Actor(_: Employee) :: Actor(_: Employee) :: tail


来源:https://stackoverflow.com/questions/25166310/scala-how-can-i-match-only-the-first-two-elements-of-an-arbitrary-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!