Example 2 : Pattern Matching
In this Example we are going to see how we can handle type mismatch error using Pattern Matching
object Main {
def main(args: Array[String]): Unit = {
val x: Any = 10;
/* Resolution: Use pattern matching */
val y: String = x match {
case s: String => s
case _ => x.toString
};
println(y);
}
}
Output :
10
How to resolve type mismatch error in Scala?
A type mismatch error in Scala is a compile-time error that occurs when the compiler detects an inconsistency between the expected type and the actual type of an expression, variable, or value. There are different methods to resolve type mismatches in Scala. In this article, we are going to discuss Different Examples to Resolve type mismatch errors.
Table of Content
- Example 1: Using Type Annotations
- Example 2 : Pattern Matching
- Example 3 : Generics