Reputation: 1548
I am trying to compare two strings in Scala. Below is the function.
def max(x:Int, y:String): String = {
| if (y=="Happy") "This is comparing strings as well"
| else "This is not so fair"
| if (x > 1) "This is greater than 1"
| else "This is not greater than 1"
| }
From some answers I assumed that I can use '==' symbol to compare the strings. I have given the following inputs and got the following outputs. what am I missing or Scala is behaving differently?
max (1,"Happy")
res7: String = This is not greater than 1
println(max(2, "sam"))
This is greater than 1
Upvotes: 0
Views: 1885
Reputation: 41957
Your max
function is returning only one string and that string is always the last if
else
statement. If you want both the comparison outputs then you should return a tuple2
of strings as
scala> def max(x:Int, y:String): (String, String) = {
| var string1 = "This is not greater than 1"
| var string2 = "This is not so fair"
| if (x > 1) string1 = "This is greater than 1"
| if (y=="Happy") string2 = "This is comparing strings as well"
| (string1, string2)
| }
max: (x: Int, y: String)(String, String)
scala> max(1, "Happy")
res0: (String, String) = (This is not greater than 1,This is comparing strings as well)
scala> res0._1
res1: String = This is not greater than 1
scala> res0._2
res2: String = This is comparing strings as well
scala> max(2, "sam")
res3: (String, String) = (This is greater than 1,This is not so fair)
I hope this answer helps
Upvotes: 1
Reputation: 830
This is happening because in scala the last reachable statement's value is the functions result. In this case for "max (1,"Happy")" the code is going inside y="happy" but right after that it is going into the else branch of if(x>1) . As that is the last statement inside the function , you are getting it as the result.
to cross check it introduce a print statement in the first if block
def max(x:Int, y:String): String = {
| if (y=="Happy") println("This is comparing strings as well")
| else "This is not so fair"
| if (x > 1) "This is greater than 1"
| else "This is not greater than 1"
| }
now call with "max(1,"Happy")"
Result: This is comparing strings as well This is not greater than 1
which shows that you are comparing strings in a right way.
Upvotes: 2