Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

type mismatch; in scala

enter image description here

Currently, I am learning Scala Language and trying to finding out the ways to print the variable without using the plus(+) operator in println() or print() method, and using String Interpolation technique.
So now I got some err. when trying to add the float value in using ${num2:.2f} in the 3rd way.

Output I want :

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

code :

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")

  }
Please help me to solve this problem, thank you!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading