转换 A => 的惯用方式序列[B] [英] Idiomatic way to convert A => Seq[B]

查看:53
本文介绍了转换 A => 的惯用方式序列[B]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将单个值转换为多个特征"的集合,而不使用可变数据结构来收集值.我想要这样的幻想结构,它使用模式匹配,但在第一次匹配后不会停止:

I'd like to convert a single value into a collection of multiple "characteristics", without using a mutable data structure to collect the values. I'd like something like this fantasy construct which uses pattern matching, but does not stop after first match:

scala> 2 multimatch {
  case i if i > 0 => "Positive"
  case i if i < 0 => "Negative"
  case i if (i % 2 == 0) => "Even"
  //yadda yadda
}
res0: Seq[java.lang.String] = List(Positive, Even)

推荐答案

使用皮条客模式、偏函数和重复参数,这是我能得到的接近程度:

Using the pimp pattern, partial functions and repeated parameters, this is how close I can get:

class MultiMatcher[A](a: A) {
  def multiMatch[B](pfs: PartialFunction[A, B]*): Seq[B] = {
    pfs.map(_.lift(a)).collect{ case Some(v) => v } 
  }
}

implicit def toMultiMatcher[A](a:A): MultiMatcher[A] = new MultiMatcher(a)

2 multiMatch (
  { case i if i > 0 => "Positive" },
  { case i if i < 0 => "Negative" },
  { case i if i % 2 == 0 => "Even" }
)
// returns Seq[java.lang.String] = ArrayBuffer(Positive, Even)

这篇关于转换 A => 的惯用方式序列[B]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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