简体   繁体   中英

drop,dropRight,take,takeRight vs substring?

I am learning Scala from Scala for the Impatient and Chapter 01 exercise has a problem

  1. What do the take, drop, takeRight, and dropRight string functions do? What advantage or disadvantage do they have over using substring?

The only advantage I see that drop (and flavors) will not throw 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? Memory efficient?

The main benefit is that it allows you to treat a String as a sequential collection of characters, much like any other Seq or List instance.

In fact, these methods (and other important transformational functions like map, flatMap and filter) are not implemented in String itself (which is, in fact, simply the Java String class, not a native-Scala class), but in the StringOps class (which extends StringLike -> ... -> SeqLike), and an implicit conversion ensures that a String is converted into a StringOps whenever you need access to these methods.

This means you can pass a String to a list-manipulation function and the function will receive a StringOps instance, work on it like any other SeqLike entity without needing to know it is actually a String, and hand back the results of the manipulation, which StringOps is designed to present back to you as a String.

If you know an entity is a String in a given piece of code, feel free to use the String-specific methods, but the availability of this implicit conversion means that you can also take advantage of a String's "character sequence"-like nature to treat it like any other list in situations where that may be convenient.

Seems that you are right. All these operations use StringOps.slice method, that delegates to String.substring method.

So, except for the overhead of wrapping string and performing bounds validation it's the same call to substring .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM