Lars Tackmann
Lars Tackmann

Reputation: 20895

Match single element in list of lists

If I have a list of the form List[Any] like this one

val list = List(List(1, 1), 2, List(3, List(5, 8)))

how do I then write a match statement that distinguishes between

  1. Single element of any non list type (i.e. 2 from above)
  2. Elements that are lists (i.e. List(1,1) and List(3, List(5, 8) from above)

or in pseudo scala

list match {
  case x:"single non-list element" => // do something with single element x
  case y:"where y is a list"       => // do something with list y
}

the usual head::tails matching does not work as head can be of type Any which includes other lists.

Upvotes: 2

Views: 1743

Answers (2)

aishwarya
aishwarya

Reputation: 1986

list foreach { 
  _ match {
    case x:List[_] => // list
    case _ => // anything else
  }
}

should work i guess

Upvotes: 5

Marimuthu Madasamy
Marimuthu Madasamy

Reputation: 13551

val (lists, nonlists) = list partition {case (x :: xs) => true case _ => false}

lists: List[Any] = List(List(1, 1), List(3, List(5, 8)))
nonlists: List[Any] = List(2)

Upvotes: 5

Related Questions