I am trying to do this lab exercise with the below solution to the provided question but unable to complete it. Please let me know where I am wrong

Pavelb,

I would like to understand why we are setting String = var1 because var1 is a Int

I modified the code from what you had to something like this
I removed the string keyword and included the string in println since the error no response on stdout was displaying in the console

def PatternMatching(var1: Int)= var1 match {

case i if i <= 0 => println(“Negative/Zero is input”)
case i if i % 2 == 0 => println(“Even number is given”)
case _ => println(“Odd number is given”)

}

}

I saw a similar example to this online but they were matching input values to 1, 2

String is the return type of the method. The equals sign in this case is a delimiter of the method definition and its body, it is not assigning anything to var1. You don’t need to explicitly specify the return type in this case, it will be inferred, but it will be String still.
You can of course match to 1, 2, 3 etc. but you will be matching to the integer value, which is most likely not what are you trying to achieve

1 Like