Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Scala - Add your own method to String class - Testingpool

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...