0

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 ?

1
  • 1
    I think your problem is that the print is only executing in the case of other days. And also it is breaking the return type of all the expression to Any. What exactly do you want to do? Commented Sep 11, 2019 at 10:59

2 Answers 2

1

Consider factoring out pattern matching into its own function

val boringDay: String => String = {
  case "Mon" => "is boring"
  case otherDay => otherDay
}

which can be used to transform the list

daysOfWeek.map(boringDay) // List(is boring, Tues, Wed, Thur, Fri, Sat, Sun)

and now use mkString to get a printable string

val output = daysOfWeek.map(boringDay).mkString("")
println(output)

which outputs

res1: String = is boringTuesWedThurFriSatSun
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

If you are yielding an Unit. It would be better yo just use the foreach syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.