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

前端 未结 3 662
你的背包
你的背包 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

提交回复
热议问题