type mismatch; found: ... required: ...
type mismatch; found: ... required: ...
DodaTech
3 min read
The “type mismatch; found: … required: …” error means the type of an expression does not match the type expected by the surrounding context.
What It Means
Scala is a statically typed language. Every expression has a type determined at compile time, and the compiler checks that types align across assignments, function arguments, return values, and pattern matches. When the actual type (“found”) differs from the expected type (“required”), compilation fails with this error showing both types.
Why It Happens
- A function’s return value type doesn’t match its declared return type.
- You pass an argument of one type where a different type is expected.
- An implicit conversion is not in scope or doesn’t exist.
- You need to explicitly convert numeric types (e.g.,
InttoDouble). - The expected type is a supertype and the found type is a subtype — but the variance is wrong.
- You forgot to import an implicit conversion.
How to Fix It
1. Fix return type mismatches
// ❌ type mismatch; found: String, required: Int
def lengthOf(text: String): Int = text
// ✅ Return the correct type
def lengthOf(text: String): Int = text.length2. Convert numeric types explicitly
// ❌ type mismatch; found: Int, required: Double
val pi: Double = 3
// ✅ Use a Double literal or explicit conversion
val pi: Double = 3.0
// or
val pi: Double = 3.toDouble3. Use .toString for string concatenation
// ❌ type mismatch — this works in many cases but can fail with ambiguous types
val age: Int = 30
val message: String = "Age: " + age // Int auto-converts to String
// When explicitly typed:
val message: String = "Age: " + age.toString4. Provide or import implicit conversions
// ❌ type mismatch; found: Int, required: MyType
class MyType(val value: Int)
val result: MyType = 42
// ✅ Define an implicit conversion
implicit def intToMyType(i: Int): MyType = new MyType(i)
val result: MyType = 42 // now works via implicit conversion5. Check function parameter types
def process(items: List[Int]): Unit = {
items.foreach(println)
}
// ❌ type mismatch; found: List[String], required: List[Int]
process(List("1", "2", "3"))
// ✅ Convert elements to Int
process(List("1", "2", "3").map(_.toInt))6. Use variance annotations or widen types
// ❌ type mismatch — List is invariant
def printStrings(items: List[Any]): Unit = {
items.foreach(println)
}
printStrings(List("a", "b")) // Actually works in Scala (List is covariant)
// For custom types, use +A for covariance or widen the argument Previous
This script contains malicious content
Next
Type mismatch: inferred type is ... but ... was expected
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro