Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit Type Conversion in Scala

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 
like image 949
Kevin Albrecht Avatar asked Oct 05 '08 04:10

Kevin Albrecht


People also ask

What is called explicit type conversion?

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.

Which is an explicit conversion of an object type of the value type?

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.

What are the different types of conversion?

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.


1 Answers

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   } } 
like image 165
Kevin Albrecht Avatar answered Sep 18 '22 05:09

Kevin Albrecht