When should you use an empty version instead of a single empty instance?

When working with collections in Scala, you usually need to use an empty collection instance for the base frame. Because empty instances extend the collection type class with the type parameter by default Nothing, it sometimes plays type inference to use directly. For instance:

scala> List(1, 2, 3).foldLeft(Nil)((x, y) => x :+ y.toString())
<console>:8: error: type mismatch;
 found   : List[String]
 required: scala.collection.immutable.Nil.type
              List(1, 2, 3).foldLeft(Nil)((x, y) => x :+ y.toString())

                                                  ^

fails, but the following two corrections are successful:

scala> List(1, 2, 3).foldLeft(Nil: List[String])((x, y) => x :+ y.toString())
res9: List[String] = List(1, 2, 3)

scala> List(1, 2, 3).foldLeft(List.empty[String])((x, y) => x :+ y.toString())
res10: List[String] = List(1, 2, 3)

Another place I've come across a similar dilemma is in defining default settings. These are the only examples that I could think of from my head, but I know that I saw others. Is one way to ensure the right type of hint is preferred over the other as a whole? Are there any places where everyone will be useful?

+1
1

Nil ( None) (, Kigyo) . , . , , .empty, , Nil: List[String], , 2 !.

.empty . , Nil: Set[String], Nil: Option[String], Set.empty[String] Option.empty[String]. , , - , .empty, . , , ?:)

, Nil None, , Set - , , Nil , , " ".

, .empty :

def printEmptyThing[K[_], T <: {def empty[A] : K[A]}](c: T): Unit = 
  println("thing = " + c.empty[String])

printEmptyThing[List, List.type](List)
printEmptyThing[Option, Option.type](Option)
printEmptyThing[Set, Set.type](Set)

:

> thing = List()

> thing = None

> thing = Set()
+1

All Articles