Example 3 : Generics
In this example we are going to see how we can handle Type mismatch error in Generics in Scala.
Error :
object Main {
def main(args: Array[String]): Unit = {
def first[A](list: List[A]): A = list.head;
/* Type Mismatch Error */
val result: Int = first(List("Scala", "Java", "Python"));
println(result);
}
}
Output :
./Main.scala:1: error: type mismatch;
found : String("Scala")
required: Int
object Main { def main(args: Array[String]): Unit = { def first[A](list: List[A]): A = list.head; /* Type Mismatch Error */ val result: Int = first(List("Scala", "Java", "Python")); println(result); }}
^
./Main.scala:1: error: type...
Solution:
object Main {
def main(args: Array[String]): Unit = {
def first[A](list: List[A]): A = list.head;
/* Resolution: Correct the type parameter */
val result: String = first(List("Scala", "Java", "Python"));
println(result);
}
}
Output :
Scala
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