E007: Type Mismatch

This error is emitted when an expression has a different type than what is expected in that context. This commonly occurs when:

  • Assigning a value to a variable with an incompatible type annotation
  • Passing an argument to a function that expects a different type
  • Returning a value from a method with an incompatible return type

Example

val x: String = 42

Error

-- [E007] Type Mismatch Error: example.scala:1:16 ------------------------------
1 |val x: String = 42
  |                ^^
  |                Found:    (42 : Int)
  |                Required: String
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  |
  | Tree:
  |
  | 42
  |
  | I tried to show that
  |   (42 : Int)
  | conforms to
  |   String
  | but none of the attempts shown below succeeded:
  |
  |   ==> (42 : Int)  <:  String
  |     ==> Int  <:  String  = false
  |
  | The tests were made under the empty constraint
   -----------------------------------------------------------------------------

Solution

// Convert the value to the expected type
val x: String = 42.toString
// Or change the type annotation to match the value
val x: Int = 42
// Or use a value of the correct type
val x: String = "42"