Home > Software engineering >  Type mismatch error when trying to format float variable inside string interpolator
Type mismatch error when trying to format float variable inside string interpolator

Time:07-18

enter image description here

Currently, I am learning Scala Language and trying to find out the ways to print the variable without using the plus ( ) operator in println() or print() methods, and rather using the String Interpolation technique.
So now I got some error. when trying to add a float value using ${num2:.2f} in the third example.

Output I want :

10 --- 10.25 --- Hello world in all cases.

The 1st and 2nd cases give me that kind of output, but not in the third case. That's why I wrote it as ${num2:.2f} but it gives me an error.

def main(args: Array[String]): Unit = {
    val num1: Int = 10
    val num2: Float = 10.2543f
    val str1: String = "Hello world"

    //    1st way
    printf("%d --- %.2f --- %s\n", num1, num2, str1)

    //    2nd way
    println("%d --- %.2f --- %s".format(num1, num2, str1))

    //    3rd way
    println(s"$num1 --- ${num2:.2f} --- $str1")
  }

Error:

Type Mismatch Error: s"${num2:.2f}" Found: (num2 : Float) Required: (0.2f : Float)

Please help me to solve this problem, thank you!

CodePudding user response:

s"$num1 --- ${num2:.2f} --- $str1"

Not sure from where you thought that would be valid.
At first glance, it even seems like invalid syntax (although is valid, but means something different of what you want).

Anyways, if we check the official docs on String interpolation we can see that the right way to do that is:

f"$num1 --- $num2%.2f --- $str1"
// val res: String = "10 --- 10.25 --- Hello world"

${num2:.2f}

This actually means that we are trying to upcast num2 to the type 0.2f; which is the literal type of the literal value 0.2f, but, of course, that fails.

  • Related