Apply several string transformations in scala

前端 未结 5 1818
温柔的废话
温柔的废话 2020-12-09 21:18

I want to perform several ordered and successive replaceAll(...,...) on a string in a functional way in scala.

What\'s the most elegant solution ? Scalaz welcome ! ;

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 22:19

    If its just a few invocations then just chain them. Otherwise I guess I'd try this:

    Seq("a" -> "b", "b" -> "a").foldLeft("abab"){case (z, (s,r)) => z.replaceAll(s, r)}
    

    Or if you like shorter code with confusing wildcards and extra closures:

    Seq("a" -> "b", "b" -> "a").foldLeft("abab"){_.replaceAll _ tupled(_)}
    

提交回复
热议问题