加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在不指定中间值的情况下链接值的操作

发布时间:2020-12-16 18:07:08 所属栏目:安全 来源:网络整理
导读:有时我执行一系列计算逐渐转换某些值,如: def complexComputation(input: String): String = { val first = input.reverse val second = first + first val third = second * 3 third} 命名变量有时很麻烦,我想避免它.我使用的一种模式是使用Option.map链接
有时我执行一系列计算逐渐转换某些值,如:

def complexComputation(input: String): String = {
  val first = input.reverse
  val second = first + first
  val third = second * 3
  third
}

命名变量有时很麻烦,我想避免它.我使用的一种模式是使用Option.map链接值:

def complexComputation(input: String): String = {
  Option(input)
    .map(_.reverse)
    .map(s => s + s)
    .map(_ * 3)
    .get
}

然而,使用Option / get对我来说并不自然.还有其他一些常见方法吗?

解决方法

实际上,它可以用 Scala 2.13.它将引入 pipe:

import scala.util.chaining._

input //"str"
 .pipe(s => s.reverse) //"rts"
 .pipe(s => s + s) //"rtsrts"
 .pipe(s => s * 3) //"rtsrtsrtsrtsrtsrts"

版本2.13.0-M1已经发布.如果您不想使用里程碑版本,可以考虑使用backport吗?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读