Search code examples
scalafor-loopmatchyield

for loop not returning value in list after matching the expression


I have used match expression using yield in for loop but I am not getting desired result

   val daysOfWeek = List("Mon","Tues","Wed","Thur","Fri","Sat","Sun")
        val day = "Mon"
         for (day <- daysOfWeek) yield
        {
          day match 
          {
            case "Mon" => "is boring"
            case otherDay => otherDay
              print(day)
          }
}

O/p of the above code is (TuesWedThurFriSatSun) but I want o/p like (is boringTuesWedThurFriSatSun)

How Can I achieve this ?


Solution

  • The issue is that you are printing within the otherday case block, so you get that as output.

    Here is what you want to achieve:

     val daysOfWeek = List("Mon","Tues","Wed","Thur","Fri","Sat","Sun")
     val day = "Mon"
     for (day <- daysOfWeek) yield
     {
         val output = day match
         {
            case "Mon" => "is boring"
            case otherDay => otherDay
         }
         print(output)
     }
    

    Output:

    is boringTuesWedThurFriSatSun