How to use pattern matching in Scala

2 Answers

0 votes
object MyClass {
    def test(x: Int): String = x match {
        case 1 => "one"
        case 2 => "two"
        case 3 => "three"
        case _ => "else"
    }
    def main(args: Array[String]): Unit = {
         println(test(2))
         println(test(88))
    }
}
     
     
     
     
/*
run:
     
two
else
     
*/

 



answered Jun 3, 2021 by avibootz
0 votes
object MyClass {
    def test(x: Any): Any = x match {
        case 1 => "one"
        case "two" => 2
        case 3 => "three"
        case y: Int => "scala.Int"
        case _ => "else"
    }
    def main(args: Array[String]): Unit = {
        println(test("two"))
        println(test("scala"))
        println(test(3))
        
        var y = 8449
        println(test(y))
    }
}
     
     
     
     
/*
run:
     
2
else
three
scala.Int
     
*/

 



answered Jun 3, 2021 by avibootz
...