Scala Type Casting with Examples
Type Casting means the conversion from one type to another type. scala also has a method of Type Casting. in scala type casting is done by using method called asInstanceOf[]
use case 1:
object prwatech {
def display[A](y:String, x:A)
{
println(y + " = " + x + " is of type " + x.getClass.getName);
}
// Main method
def main(args: Array[String])
{
var i:Int = 10;
2var f:Float = 3e5f;
var d:Double = 8.2;
4 var c:Char = 'e';
display("i", i);
display("f", f);
display("d", d);
display("c", c);
var i1 = i.asInstanceOf[Char]; //Casting
2var f1 = f.asInstanceOf[Double]; //Casting
var d1 = d.asInstanceOf[Float]; //Casting
4var c1 = c.asInstanceOf[Int]; //Casting
display("i1", i1);
display("f1", f1);
display("d1", d1);
display("c1", c1);
}
}
output
i = 10 is of type java.lang.Integer
f = 5.0 is of type java.lang.Float
d = 8.2 is of type java.lang.Double
c = e is of type java.lang.Character
i1 = is of type java.lang.Character
f1 = 5.0 is of type java.lang.Double
d1 = 8.2 is of type java.lang.Float
c1 = 101 is of type java.lang.Integer
use case 2:
object prwatech
{
// Main method
def main(args:Array[String])
{
val p = 15
// Casting value of a into float
val q = p.asInstanceOf[Float]
println("The value of p after" +
" casting into float is " + q)
}
}
output
The value of p after casting into float is 15.0
use case 3:
object prwatech
{
// Main method
def main(args:Array[String])
{
val x = 12.56
val y = 3.12
// Casting value of a into float
val z = (x/y).asInstanceOf[Int]
println("The value of z after" +
" casting into Int is " + z)
}
}
output
The value of z after casting into Int is 4
Scala Type Casting with Examples