Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
object PatternMatching1
{
def main(args: Array[String])
{
def matchText(x : Any) : Any = x match
{
case 1 => " One "
case "two" => 2
case y: Int => " You have entered an integer >2 "
case _ => "many"
println(matchText(3))
println(matchText(2))
println(matchText("two"))
println(matchText(" Oops" ))
}
}
}
object HelloWorld {
def main(args: Array[String]) {
//I have a List(1 ,2 ,3 ,4 ,5) and trying to get a sublist: List(3, 4) from it by the following way:
val list = List(1 ,2 ,3 ,4 ,5)
//0, 1, 2, 3, 4
//3, 4
var b = list.splitAt(3)._2
println(b)
println(sum(list))
def sum(xs: List[Int]): Int = xs match {
case Nil => 0
case _ :: tail if tail.length==0 => 0 // size 1
case _ :: tail if tail.length==2 => tail(1) //size 2
case _ :: tail if tail.length>2 => tail(0) + tail(1) + sum(tail.splitAt(3)._2)
}
}
}