Open In App

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.

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

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

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
Article Tags :