Here, we will demonstrate that how we can return match case value from a method? The match statement is similar to the switch statement of other programming languages. Here, we will define specific cases. In the match statement case underscore (case _) is used for the default case.
The source code to return the match case value from a method is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to return the match case
// value from method
object Sample {
def Fun(num:Any):Any = num match{
case 1 => "One"
case 2 => "Two"
case 3 => "Three"
case 4 => "Four"
case _ => "Unknown number"
}
def main(args: Array[String]) {
var res=Fun(3)
println(res)
}
}
Output:
Three
Explanation:
In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample. We defined main() function. The main() function is the entry point for the program.
Here, we also defined a Fun() method, that returns the match case value based on the given parameter
In the main() function, we called the Fun() method with value 3 and assigned the returned value to the variable res and printed the result on the console screen.
Program/Source Code:
The source code to return the match case value from a method is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Output:
Explanation:
In the above program, we used an object-oriented approach to create the program. Here, we created an object Sample. We defined main() function. The main() function is the entry point for the program.
Here, we also defined a Fun() method, that returns the match case value based on the given parameter
In the main() function, we called the Fun() method with value 3 and assigned the returned value to the variable res and printed the result on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer