在Scala中同时打印和返回值的惯用方式 [英] Idiomatic way of print and return value at the same time in Scala

查看:27
本文介绍了在Scala中同时打印和返回值的惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中打印(或做任何我需要做的事情)和返回值的惯用方式是什么?例如,

What is the idiomatic way of printing (or doing whatever thing I need to do) and returning value in Scala? For example,

Seq(1,2,3)
  .map(_ * 2)
  .xxx(println) // Here I want to print the intermediate sequence
  .foldLeft(0)(_ + _)

我能想到的一种方法是使用隐式,但我真的不喜欢自己修改标准库.

One way I can think of is using implicit but I don't really like to monkey patch standard library myself.

在 Ruby 中我们可以使用 Object#tap

In Ruby we can use Object#tap

[1,2,3]
  .map { |i| i * 2 }
  .tap { |i| puts i }
  .reduce(0) { |x, i| x += i }

推荐答案

Object#Ruby 中的 tap 基本上是 K 组合器的变体.我不相信 Scala 标准库中有实现,但添加自己的很容易:

Object#tap in Ruby is basically a variant of the K combinator. I don't believe there is an implementation in the Scala standard library, but it is easy to add your own:

implicit class TapExtension[T](o: => T) {
  def tap(f: T => Unit) = { f(o); o }
}

注意:这是一个隐式转换,它不是猴子补丁.

Note: This is an implicit conversion, it is not monkey-patching.

然后,您可以像这样使用它:

Then, you can use it like so:

Seq(1,2,3)
  .map(_ * 2)
  .tap(println)
  .foldLeft(0)(_ + _)

这篇关于在Scala中同时打印和返回值的惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆