Concatenate string and integer

Hi, I am new to scala and working on writing a scala function which will find the maximum value. In the println() I want to print which variable has the maximum value. I get error type mismatch -> "maxValue A = " + A.toString when trying to do the concatenation.

var A = 10
var B = 20

def maxValue(A: Int, B: Int): String = {
  if (A > B) {
    println("maxValue A = " + A.toString)
  }
  else {
    println("maxValue B = " + B.toString)
  }
}

So the error is quite simple.
You said that your function would return a String, but you are trying to return a call to println which is not an String but rather an Unit.

So, you can either remove the println and just leave the String or fix the type definition.

For example:

// By convention variables start with a lowercase letter.
def maxValue(a: Int, b: Int): Unit = {
  if (a > b) {
    // Prefer String interpolation over concatenation.
    println(s"maxValue A = ${a}")
  }
  else {
    println("maxValue B = ${b}")
  }
}

// Always use vals, unless you really need mutability (you shouldn't need that most of the time)
val a = 10
val b = 20

// This will return the Unit ()
// And will print in console: "maxValue B = 20"
maxValue(a, b)

Hope everything is clear :smiley:

2 Likes

Thanks very much for the response. what difference would it make to use s" " and " " or was it a typo.

That s is to signal that the next String is to be interpolated.

1 Like

Hi, Thanks very much.