Home »
Scala »
Scala Programs
Scala program to print the type of the variable
Here, we are going to learn how to print the type of the variable in Scala programming language?
Submitted by Nidhi, on April 26, 2021 [Last updated : March 09, 2023]
Scala – Print the Type of a Variable
In this program, we will get the type of variable using the getClass method and print the result on the console screen.
Scala code to print the type of the variable
The source code to print the type of the variable is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to print the type
// of the variable
object Sample{
def main(args: Array[String]): Unit = {
var var1:Char='A'
var var2:Int=101
var var3:Float=10.23F
var var4:String="Hello"
println("Type of var1: "+var1.getClass)
println("Type of var2: "+var2.getClass)
println("Type of var3: "+var3.getClass)
println("Type of var4: "+var4.getClass)
}
}
Output
Type of var1: char
Type of var2: int
Type of var3: float
Type of var4: class java.lang.String
Explanation
In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample. We defined main() function. The main() function is the entry point for the program.
In the main() function, we created four variables var1, var2, var3, var4 initialized with some values. After that, we get the type of variables using the getClass method and print the result on the console screen.
Scala Basic Programs »