Back to Scala3

E209: Format Interpolation Error

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

3.8.41.7 KB
Original Source

E209: Format Interpolation Error

This error occurs when there is a type mismatch or invalid format specifier in an f"" string interpolator. The f interpolator uses Java's Formatter syntax and requires that the format specifiers match the types of the interpolated values.

Example

scala
def example =
  val s = "hello"
  f"$s%d"

Error

scala
-- [E209] Interpolation Error: example.scala:3:5 -------------------------------
3 |  f"$s%d"
  |     ^
  |     Found: (s : String), Required: Int, Long, Byte, Short, BigInt

Solution

Use the correct format specifier for the value's type. For strings, use %s:

scala
def example =
  val s = "hello"
  f"$s%s"

Common Format Specifiers

Here are some common format specifiers and their expected types:

SpecifierExpected TypeExample
%sAny (converted to String)f"$name%s"
%dInt, Long, Byte, Short, BigIntf"$count%d"
%fDouble, Float, BigDecimalf"$price%f"
%xInt, Long, Byte, Short, BigIntf"$hex%x"
%cChar, Byte, Short, Intf"$char%c"
%bBoolean (or any for null check)f"$flag%b"
%eDouble, Float, BigDecimalf"$scientific%e"

Example with Numeric Formatting

scala
def formatNumbers =
  val price = 19.99
  val count = 42
  f"Price: $$$price%.2f, Count: $count%04d"
<!-- 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>