Option 包装一个值是一个好的模式吗? [英] Is Option wrapping a value a good pattern?
问题描述
我最近编写了以下 Scala 代码:
I recently wrote the following bit of Scala:
val f: File = ... // pretend this file came from somewhere
val foo = toFoo(io.Source.fromFile(f).mkString)
我真的不喜欢这种流动的方式.要了解发生了什么,您必须从中间的 f
开始,向左阅读 fromFile
,向右阅读 mkString
,再次向左阅读toFoo
.呃.
I really didn't like the way this flowed. To understand what's happening, you have to start with f
in the middle, read left to fromFile
, read right to mkString
, read left again to toFoo
. Ugh.
特别是在习惯了序列的函数转换之后,这很难阅读.我的下一次尝试如下所示:
Especially after getting used to functional transformations of sequences, this is difficult to read. My next attempt looks like this:
val foo = Some(f)
.map(io.Source.fromFile)
.map(_.mkString)
.map(toFoo)
.get
我更喜欢这个流程.您可以看到发生了什么 这是对 Option
类的一个很好的使用吗?还是我滥用了?有没有更好的模式可以用来实现相同的流程?
I like the flow of this much better. You can see what happens Is this a good use of the Option
class? Or am I abusing it? Is there a better pattern that I can use to achieve the same flow?
推荐答案
这完全没问题.但是,Scalaz 中有一种方法 |>
做得更好,如果您不想要所有 Scalaz,也可以自己创建:
This is perfectly okay. However, there is a method |>
in Scalaz that does one better, and you can create it yourself if you don't want all of Scalaz:
class Piper[A](a: A) { def |>[B](f: A => B) = f(a) }
implicit def pipe_everything[A](a: A) = new Piper(a)
f |> io.Source.fromFile |> {_.mkString} |> toFoo
就我个人而言,我倾向于编写大量需要括号的代码,并且在大多数情况下我更喜欢方法而不是运算符,因此在我的代码中我通常称 |>
use",但它同样的交易:
Personally, I tend to write a lot of code that requires parentheses and I like methods better than operators in most cases, so in my code I normally call |>
"use", but it's the same deal:
f.use(io.Source.fromFile).use(_.mkString).use(toFoo)
<小时>
在 Scala 2.11 或更高版本中,您可以使用(稍微)更少的语法获得相同的行为和改进的性能:
In Scala 2.11 or later, you can get the same behavior and improved performance with (slightly) less syntax:
implicit class Piper[A](private val a: A) extends AnyVal {
def |>[B](f: A => B) = f(a)
}
这篇关于Option 包装一个值是一个好的模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!