Open In App

How to resolve type mismatch error in Scala?

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Scala
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.

Scala
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

Scala
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 :

Scala
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:

Scala
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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads