add method to string class scala
To add a method to the String class in Scala, you can use implicit classes. Implicit classes allow you to add new methods to existing classes without modifying their original source code. Here's an example of how you can add a method to the String class:
implicit class StringExtensions(val str: String) extends AnyVal {
def customMethod: String = {
// Your custom logic here
str + " is extended!"
}
}
In this example, we define an implicit class called StringExtensions
that takes a String
parameter str
. The StringExtensions
class is defined as AnyVal
to ensure that it is compiled as a value class, which improves performance. The customMethod
is the method we are adding to the String
class, and it can be called on any instance of String
. Inside the customMethod
, you can implement your custom logic.
Once you have defined the implicit class, you can use the customMethod
on any String
object as if it were a built-in method:
val myString = "Hello"
val extendedString = myString.customMethod
println(extendedString) // Output: "Hello is extended!"
By using implicit classes, you can extend the functionality of the String class in Scala without modifying its original source code.