【问题标题】:scala having a case statement inside a lambdascala 在 lambda 中有一个 case 语句
【发布时间】:2016-10-03 20:15:09
【问题描述】:

为什么不能在 lambda 函数中包含 case 语句?我的代码看起来像

def f(list:List[String]):List[Int] = list.map( _ match{ case _.length > 1 => _.length else 1})

input 
"mike" 
"tom"
"t"
" "

output
4  
3
1
1

如您所见,我正在尝试在 lambda 中做一个案例。我用语法尝试了很多方法。

【问题讨论】:

  • 您的 3 个通配符 (_) 应该是什么?同一个参数? 3个不同的参数?如果您只有两种可能性,而且您没有匹配任何模式,为什么要使用 match 而不是 if
  • 也许如果你能把你想要的代码写成一个完整的函数,你想让你的 lambda 做什么会更清楚。

标签: list scala collections


【解决方案1】:

您似乎正在尝试使用 保护子句,您可能希望查看a tutorial on match statements

但是,您所做的根本不需要 match 语句。

list.map(x => math.max(1, x.length))

或者,如果max 不存在并且我们不想调用x.length 两次,我们可以分配一个变量:

list.map{ x =>
  val len = x.length
  if (len > 1) len else 1
}

或者,我们可以使用 match 语句,可以带有保护子句或裸露:

list.map(_.length match { case x if x > 1 => x; case _ => 1 })
list.map(_.length match { case x => if (x > 1) x else 1 })

请注意,_ 不是变量。您不能重复使用它。它的意思是,交替地,“忽略这个”,“让它成为一个函数”,“放入下一个变量是什么”。如果你想要一个可以重复引用的变量,你必须给它命名(例如x)。

另请注意,else 不是case 语句的“如果不是”替代方案。如果您想要一个默认的 catch-whatever-remains 语句(而且您应该这样做!),请使用 case _ =>

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多