What is string intern() in Scala?
The method intern() in Scala is used to return an interned string. By interned, it means that the method returns a canonical presentation of the string object that is passed.
In programming, a canonical representation means according to rules. The canonical representation of a string object is the textual part of the string itself with the escape values like \n, \t, \' applied to the string.
Syntax
string.intern()
Calling the method returns a canonical representation of the string that is being used.
Code
object Main extends App {// introducting some stringval str1 = "Hello world!"val result = "Hello, \t \t Welcome to Educative.".intern()// Displays output as string itself, with \t applied.println(str1.intern())println(result)// a string is same as its intern string.println("is str1 == str1.intern? ", str1 == str1.intern())}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved