Difference between a Seq and a List in Scala

前端 未结 5 1119
不思量自难忘°
不思量自难忘° 2020-11-29 14:26

I\'ve seen in many examples that sometimes a Seq is being used, while other times is the List...

Is there any difference, other than the former one being a Scala typ

5条回答
  •  庸人自扰
    2020-11-29 15:05

    Seq is a trait that List implements.

    If you define your container as Seq, you can use any container that implements Seq trait.

    scala> def sumUp(s: Seq[Int]): Int = { s.sum }
    sumUp: (s: Seq[Int])Int
    
    scala> sumUp(List(1,2,3))
    res41: Int = 6
    
    scala> sumUp(Vector(1,2,3))
    res42: Int = 6
    
    scala> sumUp(Seq(1,2,3))
    res44: Int = 6
    

    Note that

    scala> val a = Seq(1,2,3)
    a: Seq[Int] = List(1, 2, 3)
    

    Is just a short hand for:

    scala> val a: Seq[Int] = List(1,2,3)
    a: Seq[Int] = List(1, 2, 3)
    

    if the container type is not specified, the underlying data structure defaults to List.

提交回复
热议问题