Back to Scala3

E007: Type Mismatch

docs/_docs/reference/error-codes/E007.md

3.8.41.7 KB
Original Source

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

scala
val x: String = 42

Error

scala
-- [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

scala
// Convert the value to the expected type
val x: String = 42.toString
scala
// Or change the type annotation to match the value
val x: Int = 42
scala
// Or use a value of the correct type
val x: String = "42"
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>