Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop,dropRight,take,takeRight vs substring?

Tags:

string

scala

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?

like image 369
daydreamer Avatar asked Jul 29 '15 21:07

daydreamer


2 Answers

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.

like image 136
Shadowlands Avatar answered Nov 12 '22 15:11

Shadowlands


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.

like image 43
Aivean Avatar answered Nov 12 '22 15:11

Aivean