Example 1: Using Type Annotations
In this example, we are going to see how we can handle type mismatch errors using explicit type annotation or conversion.
Error:
object Main {
def main(args: Array[String]): Unit = {
val x = "10";
/* Type mismatch: found: String, required: Int*/
val y : Int = x;
print(y);
}
}
Output :
./Main.scala:1: error: type mismatch;
found : String
required: Int
object Main { def main(args: Array[String]): Unit = { val x = "10"; /* Type mismatch: found: String, required: Int*/ val y : Int = x; print(y); }}
Solution :
Below is the solution of the above type mismatch error using explicit type annotation or conversion.
object Main {
def main(args: Array[String]): Unit = {
val x = "10";
/*solution: Use explicit type annotation or conversion*/
val y : Int = x.toInt;
print(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