user438454534
user438454534

Reputation: 3689

Scalaz.NonEmptyList vs Scala.List?

Can someone explain why should I use Scalaz's NonEmptyList over Scala's List?

In a immutable application it does not make much sense to create an empty List

  1. So should I always use NonEmptyList in an immutable application ?
  2. Why else would I use scalaz's NonEmptyList over scala's Listother than the obvious reason that it guarantee at least one element in the list ?

Upvotes: 0

Views: 395

Answers (1)

rethab
rethab

Reputation: 8443

Scala's collections have a number of unsafe methods. These include head, last etc. Unsafe means they will throw an exception if the collection is empty. Now you can say "I am really sure this collection will not be empty at runtime, so my code is safe". However, somebody comes along, changes your the code etc.

So, essentially, that scalaz type gives you static safety, because if you statically know that the collection will not be empty, then it is safe to call head etc.

Upvotes: 4

Related Questions