scala – 将两种匹配模式合二为一
发布时间:2020-12-16 18:42:53 所属栏目:安全 来源:网络整理
导读:如何结合(以一种很好的方式)两个 Scala match’es? 首先,我必须测试Option是否是有效值: myOption match { case Some(op) = doSomethingWith(op) case None = handleTheError() 那么如果op有效,我想测试另一种模式: Path(request.path) match { case "wor
如何结合(以一种很好的方式)两个
Scala match’es?
首先,我必须测试Option是否是有效值: myOption match { case Some(op) => doSomethingWith(op) case None => handleTheError() 那么如果op有效,我想测试另一种模式: Path(request.path) match { case "work" => { println("--Let's work--") } case "holiday" => { println("--Let's relax--") } case _ => { println("--Let's drink--") } } 我可以这样组合它们: myOption match { case Some(op) => doSomethingWith(op) Path(request.path) match { case "work" => { println("--Let's work--") } case "holiday" => { println("--Let's relax--") } case _ => { println("--Let's drink--") } } case None => handleTheError() 但是,它感觉很草率.是否有更好的方式以某种方式组合它们. 更新 道歉,我应该更好地解释.我实际上试图找出是否存在用于简化(或分解)这些控制结构的已知模式.例如(假设这是真的): x match { case a => { y match { case c => {} case d => {} } } case b => {} } 等于 x -> y match { case a -> c => {} case a -> d => {} case b => {} } 如果有人已经确定了一些控制流的重构模式,那我只是在徘徊,就像代数中的2(x y)= 2x 2y 解决方法
你可以做
myOption map { success } getOrElse handleTheError 或者用scalaz, myOption.cata(success,handleTheError) 成功就像是 def success(op: Whatever) = { doSomethingWith(op) Path(request.path) match { case "work" => println("--Let's work--") case "holiday" => println("--Let's relax--") case _ => println("--Let's drink--") } } 更新 你的伪代码 x -> y match { case a -> c => {} case a -> d => {} case b => {} } 可以直译为scala as (x,y) match { case (a,c) => {} case (a,d) => {} case (b,_) => {} } 如果内部匹配器只有很少的选项(在这种情况下为c和d),它看起来很好(这可能是你想要的),但它会导致代码重复(重复模式a).所以,一般来说,我更喜欢map {} getOrElse {},或者在较小的函数上分离模式匹配器.但我再说一遍,在你的情况下它看起来很合理. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容