When retrieving everything but the last element of a sequence, do not use
init
.dropRight(1)
is often what you want to use.
Some collections are empty, and init
deals with them by throwing an exception:
Seq.empty[Int].init
// java.lang.UnsupportedOperationException: empty.init
// at scala.collection.TraversableLike.init(TraversableLike.scala:454)
// at scala.collection.TraversableLike.init$(TraversableLike.scala:453)
// at scala.collection.AbstractTraversable.init(Traversable.scala:108)
// at repl.Session$App$$anonfun$1.apply(traversable_init.md:9)
// at repl.Session$App$$anonfun$1.apply(traversable_init.md:9)
dropRight(1)
, on the other hand, will yield a reasonable value: the empty list.
Seq(1, 2, 3).dropRight(1)
// res0: Seq[Int] = List(1, 2)
Seq.empty[Int].dropRight(1)
// res1: Seq[Int] = List()
Note that this is not always what you want to do. There are scenarios in which you must deal with the empty case explicitly - as a stop condition in a recursive function, say. It’s just that, often, getting the empty list when you ask for everything but the last element of an empty list is perfectly reasonable.
Linter | Rule |
---|---|
WartRemover |