Confusion about matching

Just a naive question. Consider matching

fruits match {
     case List("apples", e @ _*) => "a"::List(e)
     case _ => List()}

on the following list
val fruits = List("apples", "oranges", "pears", "mangos")

why am I getting the result
List(a, List(oranges, pears, mangos))
and not
List(a, oranges, pears, mangos)

I know it is a trivial question, but somehow I always stumble at it.

e is already a List – by wrapping it again in "a"::List(e), you’re making a List of List, which isn’t what you want. I think that turning that into simple "a" :: e will give you the right result.

No, e is a sequence, as far as I understand. Your solution does not work. Happy that not only me falls in this trap :grinning_face_with_smiling_eyes:

You can do "a" :: e.toList but that is doing a lot of copies.

Is better if one forget about the fancy features of pattern matching and just focus on the basic ones:

fruits match {
  case "apples" :: tail =>
    "a" :: tail

  case _ =>
    List.empty[String]
}
1 Like

You are helpful as usual, thank you! But apart from efficiency, isn’t Seq already implemented as List?

val y = Seq("oranges", "pears", "mangos")
//val y: Seq[String] = List(oranges, pears, mangos)

Not necessarily, Seq is an interface, many collections implement such an interface.
List is one of such implementations, also being the default implementation that uses the apply method of the Seq companion.

But, when you have a Seq you should not assume it is a List because it may not.

Sorry for repeated questions, but can you give a simple example where Seq is not a List.

val aSeq1: Seq[Int] = Vector(1, 2, 3)
val aSeq2: Seq[Int] = LazyList(1, 2, 3)
val aSeq3: Seq[Int] = Stream(1, 2, 3)
val aSeq4: Seq[Int] = ArraySeq(1, 2, 3)
val aSeq5: Seq[Int] = Queue(1, 2, 3)
val aSeq6: Seq[Int] = 1 to 10
val aSeq7: Seq[Int] = new Seq[Int] { ... }
1 Like

Thank you for your patience. I was totally confused :slight_smile:

All the collection types are explained in detail in the “Programming in Scala” book, chapter 24 “Collections in Depth”. It will get rid of all your confusion completely.

1 Like

Total n00b here, but trying lots of things in a playground and having fun.
I got this to work:

  val fruits = List("apples", "oranges", "pears", "mangos");
  val matched = fruits match {
    case List("apples", e @ _*) => "a" ++: e
    case _ => List()
  }

List(a, oranges, pears, mangos)

Regards, Mark.