List.empty vs. List() vs. new List()

前端 未结 3 663
你的背包
你的背包 2021-02-05 03:25

What the difference between List.empty, List() and new List()? When should I use which?

相关标签:
3条回答
  • 2021-02-05 03:43

    For the creations of an empty list, as others have said, you can use the one that looks best to you.

    However for pattern matching against an empty List, you can only use Nil

    scala> List()
    res1: List[Nothing] = List()
    
    scala> res1 match {
         | case Nil => "empty"
         | case head::_ => "head is " + head
         | }
    res2: java.lang.String = empty
    

    EDIT : Correction: case List() works too, but case List.empty does not compile

    0 讨论(0)
  • 2021-02-05 03:49

    First of all, new List() won't work, since the List class is abstract. The other two options are defined as follows in the List object:

    override def empty[A]: List[A] = Nil
    override def apply[A](xs: A*): List[A] = xs.toList
    

    I.e., they're essentially equivalent, so it's mostly a matter of style. I prefer to use empty because I find it clearer, and it cuts down on parentheses.

    0 讨论(0)
  • 2021-02-05 03:59

    From the source code of List we have:

    object List extends SeqFactory[List] {
      ...
      override def empty[A]: List[A] = Nil
      override def apply[A](xs: A*): List[A] = xs.toList
      ... 
    }
    
    case object Nil extends List[Nothing] {...}
    

    So we can see that it is exactly the same

    For completeness, you can also use Nil.

    0 讨论(0)
提交回复
热议问题