Drop, dropRight, take, takeRight vs substring?

I am learning Scala from Scala for Impatient and Chapter 01 exercise has problems

  1. What to do with string functions take, drop, takeRight and dropRight to do? What advantage or disadvantage do they have when using a substring?

The only advantage I see is that drop (and flavors) will not throw an IndexOutOfBoundsException

For example:

 scala> "Hello World!" dropRight 100 res26: String = "" scala> "Hello World!" substring 100 java.lang.StringIndexOutOfBoundsException: String index out of range: -88 at java.lang.String.substring(String.java:1919) ... 33 elided 

What else? Effective memory?

+7
string scala
source share
2 answers

The main advantage is that it allows String to be treated as a sequential character set, like any other Seq or List instance.

In fact, these methods (and other important transformation functions such as map, flatMap, and filter) are not implemented in String itself (it is, in fact, just a Java String class, not a native-Scala class), but in a StringOps class (which extends StringLike → ... → SeqLike), and the implicit conversion ensures that String is converted to StringOps whenever you need access to these methods.

This means that you can pass String to the list management function, and the function will receive an instance of StringOps, working on it like any other SeqLike object, without having to know that it is actually a string, and send the results that StringOps is intended to be presented to you as a string.

If you know that an entity is a string in a given piece of code, feel free to use String-specific methods, but the availability of this implicit conversion means that you can also use the String character sequence - like any other list, in situations when it can be convenient.

+11
source share

You seem to be right. All of these operations use the StringOps.slice method, which delegates the String.substring method.

Thus, with the exception of the overhead of the wrapping string and performing border checks, it calls the same substring call.

+4
source share

All Articles