Is Option wrapping a value a good pattern?

后端 未结 3 1825
攒了一身酷
攒了一身酷 2021-02-05 22:52

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)
         


        
3条回答
  •  无人共我
    2021-02-05 23:44

    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
    

    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)
    

    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)
    }
    

提交回复
热议问题