Scala – Add your own method to String class

Sometimes, if existing methods does not solve your purpose, you can add your own method into string class. Scala allows you to add a method easily.

Example – Suppose you want to create a method which increments each character by one and prints the next character of whole string. It is possible to write a method with the help of implicit class. As you can see below, we have defined an object and inside that object we have defined an implicit class.

A method named nextchar is created which will read the string character by character and increment each character to the next consecutive character. If it finds character as ‘z’, it will provide the next character as ‘a’.

object AddYourMethod extends App{

  println("rbzkz".nextChar)

  implicit class formatting(s:String){
    def nextChar = s.map(x=> if(x=='z') 'a' else (x+1).toChar)
  }
}
Output: scala

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...