for循环在匹配表达式后不返回列表中的值
for loop not returning value in list after matching the expression
我在 for 循环中使用了使用 yield 的匹配表达式,但我没有得到想要的结果
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 上面的代码是 (TuesWedThurFriSatSun) 但我想要 o/p 像 (is boringTuesWedThurFriSatSun)
我怎样才能做到这一点?
问题是您在 otherday case 块中打印,因此您将其作为输出。
这是您想要实现的目标:
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)
}
输出:
is boringTuesWedThurFriSatSun
考虑将模式匹配分解到它自己的函数中
val boringDay: String => String = {
case "Mon" => "is boring"
case otherDay => otherDay
}
可用于转换列表
daysOfWeek.map(boringDay) // List(is boring, Tues, Wed, Thur, Fri, Sat, Sun)
现在使用 mkString
获取可打印字符串
val output = daysOfWeek.map(boringDay).mkString("")
println(output)
输出
res1: String = is boringTuesWedThurFriSatSun
我在 for 循环中使用了使用 yield 的匹配表达式,但我没有得到想要的结果
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 上面的代码是 (TuesWedThurFriSatSun) 但我想要 o/p 像 (is boringTuesWedThurFriSatSun)
我怎样才能做到这一点?
问题是您在 otherday case 块中打印,因此您将其作为输出。
这是您想要实现的目标:
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)
}
输出:
is boringTuesWedThurFriSatSun
考虑将模式匹配分解到它自己的函数中
val boringDay: String => String = {
case "Mon" => "is boring"
case otherDay => otherDay
}
可用于转换列表
daysOfWeek.map(boringDay) // List(is boring, Tues, Wed, Thur, Fri, Sat, Sun)
现在使用 mkString
获取可打印字符串
val output = daysOfWeek.map(boringDay).mkString("")
println(output)
输出
res1: String = is boringTuesWedThurFriSatSun