scala函数的流水线组合
回顾前面的场景,如果还还需要更新Song的一些信息,可以通过addThen或者 Function 伴生对象上的 chain 方法来实现流水线组合功能:
object SongDemo3 { /** * 将歌手名中的“华仔”统一为“刘德华” * 过滤掉“纯音乐”的歌手名 * * @return */ def updateSingerName = (song: Song2) => { song.singers = song.singers.map(sn => if (sn.equals("华仔")) "刘德华" else sn) .filter(sn => !sn.equals("纯音乐") && sn.length > 0).distinct song } /** * 热度值小于0的,统一为0 * * @return */ def updateHot = (song: Song2) => if (song.hot < 0) song.copy(hot = 0) else song def output = (song: Song2) => println(s"id:${song.id}\tname:${song.name}\tsingers:${song.singers}\thot:${song.hot}") def main(args: Array[String]) { val songs = List( Song2(1, "今天", List("刘德华"), 101), Song2(2, "笨小孩", List("刘德华", "华仔"), 20), Song2(3, "七里香", List("周杰伦"), 501), Song2(4, "吻别", List("张学友"), 20000), Song2(5, "浮夸", List("陈奕迅"), 99), Song2(6, "市集", List("纯音乐"), -1) ) val pipeline = Function.chain(Seq(updateSingerName, updateHot)).andThen(output) songs.foreach(pipeline) } }
输出结果:
id:1 name:今天 singers:List(刘德华) hot:101
id:2 name:笨小孩 singers:List(刘德华) hot:20
id:3 name:七里香 singers:List(周杰伦) hot:501
id:4 name:吻别 singers:List(张学友) hot:20000
id:5 name:浮夸 singers:List(陈奕迅) hot:99
id:6 name:市集 singers:List() hot:0
posted on 2017-03-20 09:37 taich-flute 阅读(365) 评论(0) 编辑 收藏 举报