Home »
Scala
How to convert enum to string in Scala?
By IncludeHelp Last updated : October 20, 2024
Before learning about the conversion let's discuss for basics about enum and strings.
Scala Enumeration
enum is also known as Enumeration is a set of named constants that are used in modeling in programming languages.
Example
object programming_language extends Enumerations {
val c, c++, scala, java, javascript, python = Value
}
Scala String
String in Scala is a collection of characters. It is a mutable object i.e. once created the string values cannot be changed.
Example
val string : String = "includehelp.com"
Convert Enum to String
We can convert an enum object to string in Scala. For this, we have to provide a string value to all the named constants which will be then printed. The conversion will be done using the toString() method present in the Scala library.
Syntax
enum_object.value.toString
Scala program to convert enum to string
// Program to convert enum to string in Scala
object MyClass {
// Creating a Enum
object programmingLang extends Enumeration {
val C = Value("C programming language")
val java = Value("Java programming language")
val scala = Value("Scala programming language")
val javascript = Value("JavaScript programming language.")
}
def main(args: Array[String]) {
// Converting to String
println("The string conversion of each value of Enum is :")
println(programmingLang.C.toString)
println(programmingLang.java.toString)
println(programmingLang.scala.toString)
println(programmingLang.javascript.toString)
}
}
Output
The string conversion of each value of Enum is :
C programming language
Java programming language
Scala programming language
JavaScript programming language.
Description
In the above code we have created an enumeration named programmingLang with 4 values and then using the tostring method we have converted enum value to string which is printed to output using println() method.