M.Regmi M.Regmi - 3 months ago 8
Scala Question

How can I pass the parameter in the function num()?

object MatchTest4 extends App{

def matchTest(x: Any): Any = x match {

case 1 => def num(p: Int, q: Int): Unit = {
val sum = p + q
println(sum)
}

case 2 => def num(p: Int, q: Int): Unit = {
val sub = p - q
println(sub)
}

case 3 => def num(p: Int, q: Int): Unit = {
val mul = p * q
println(mul)
}

case 4 => def num(p: Int, q: Int): Unit = {
val div = p / q
println(div)
}

case _ => println("Invalid Choice")
}

println("Enter Your Choice")
val b= readInt()
println(matchTest(b))
}


Now I want to give parameter to the function
num()
.Is it possible?

Answer

The below code should accomplish what you are trying to do. The changes I made were:

  1. Removed the return type for the matchTest. Scala will automatically infer the return type as a function value.

  2. Replaced the method definitions "num" by anonymous functions.

  3. Modified the signature of your wildcard pattern match to also return a function consistent with other pattern matches. (This is a hack, I hope someone knows a better way)

You can run your returned anonymous functions like matchTest(4)(2,3) etc.

def matchTest(x: Any) = x match {

case 1 => (p: Int, q: Int) => {

  val sum = p + q

  println(sum)

}


case 2 => (p: Int, q: Int) => {

  val sub = p - q

  println(sub)

}

case 3 => (p: Int, q: Int) => {


  val mul = p * q


  println(mul)


}

case 4 => (p: Int, q: Int) => {

  val div = p / q

  println(div)

}
case _ => println("Invalid Choice"); (a: Int, b: Int) =>  println("Invalid Choice")
}