It is safe to get the tail of an array

I called tail on Array , but saw a warning.

 scala> val arr = Array(1,2) arr: Array[Int] = Array(1, 2) scala> arr tail warning: there were 1 feature warning(s); re-run with -feature for details res3: Array[Int] = Array(2) 

Scaladocs for Array shows UnsupportedOperationException [will be thrown] if the mutable indexed sequence is empty.

Is there a safe, will not throw an exception, a way to get the tail of an array?

+4
source share
3 answers

Is there a safe, will not throw an exception, a way to get a tail array?

You can use drop :

 scala> Array(1, 2, 3).drop(1) res0: Array[Int] = Array(2, 3) scala> Array[Int]().drop(1) res1: Array[Int] = Array() 

Also note that, as pointed out by @TravisBrown in the comment below, drop does not distinguish between an empty tail (for collections with one element) and no tail (for empty collections), since in both cases drop(1) returns an empty collection.

+12
source

First of all, the warning has nothing to do with the fact that you are using an unsafe method. If you restart REPL with -feature , you will see the following:

 scala> arr tail <console>:9: warning: postfix operator tail should be enabled by making the implicit value language.postfixOps visible... 

And a pointer to the documentation for scala.language.postfixOps , which includes the following note:

Postfix statements interact poorly with semicolon pins. Most programmers avoid them for this reason.

This is good advice. The ability to write arr tail instead of arr.tail not worth the fuss.

Now about the security issue. The standard library does not provide tailOption for collections, but you can get the same effect using headOption and map :

 scala> val arr = Array(1, 2) arr: Array[Int] = Array(1, 2) scala> arr.headOption.map(_ => arr.tail) res0: Option[Array[Int]] = Some([ I@359be9fb ) 

If this is too verbose or opaque or inefficient for you, you can easily create an implicit class that will add a more nice tailOption to Array (or Seq , or IndexedSeq , etc.).

+6
source

See @TravisBrown answer for your warning.

I personally would use scala.util.Try , and not its rather smart card on the head of the array:

 scala> val arr = Array(0, 1, 2) arr: Array[Int] = Array(0, 1, 2) scala> scala.util.Try {arr.tail} foreach {t => println(t.mkString(","))} 1,2 
0
source

Source: https://habr.com/ru/post/1500832/


All Articles