Lets say I have the following code:
abstract class Animal case class Dog(name:String) extends Animal var foo:Animal = Dog("rover") var bar:Dog = foo //ERROR!
How do I fix the last line of this code? Basically, I just want to do what, in a C-like language would be done:
var bar:Dog = (Dog) foo
Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.
Type conversion happens when we assign the value of one data type to another. If the data types are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to be converted explicitly which is known as Explicit Type conversion. For example, assigning an int value to a long variable.
There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting.
I figured this out myself. There are two solutions:
1) Do the explicit cast:
var bar:Dog = foo.asInstanceOf[Dog]
2) Use pattern matching to cast it for you, this also catches errors:
var bar:Dog = foo match { case x:Dog => x case _ => { // Error handling code here } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With