Peter Krauss
Peter Krauss

Reputation: 13930

Elegant String getter is possible? How to?

Imagine a text transformation, for example to reduce a Scala String containing Unix path,

val thePath = "this/is/a/long/path/Hello.txt"
thePath.replaceAll("^.+/", "")  // reduced to "Hello.txt"

My dream (it is not necessary but it is elegant) is to create a general property for all my String datatypes that returns the transformation,

thePath.cutPath   // results in "Hello.txt"

there are a way to define this implicit method cutPath for String datatype (into some scope) with Scala?

Upvotes: 0

Views: 42

Answers (1)

Tim
Tim

Reputation: 27356

This is straightforward to implement using an implicit class:

implicit class myAddOns(s: String) {
  def cutPath = s.replaceAll("^.+/", "")
}

thePath.cutPath // results in "Hello.txt"

This effectively adds the cutPath method to any String value.

Upvotes: 3

Related Questions