次のようなものが欲しいです。
val onlyNice = true;
val users: List[String] = getNames()
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.filter(p => isNice) // here i would need to apply this filter only if `onlyNice` is true
.map(p => countryOf(p));
つまり、次のisNice
場合にのみフィルターを適用しますonlyNice==true
。私は次のようにそれを行うことができます:
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.filter(p => !onlyNice || isNice)
.map(p => countryOf(p));
ただし、onlyNice が false の場合でもすべてのリストをトラバースしているため、パフォーマンスが低下します。
次のようにできます。
val tmp = users
.filter(_.contains("john")
.map(._toUpperCase)
val tmp2 = if (onlyNice) tmp.filter(isNice) else tmp
val result = tmp2.
.map(p => countryOf(p));
しかし、これは読みにくいです。
これは私にとって良い一般化された解決策のようです:
implicit class ObjectHelper[A](o: A) {
def transform[B](f: A => B): B = f(o)
}
val result = users
.filter(_.contains("john")
.map(._toUpperCase)
.transform(list => if (onlyNice) list.filter(isNice) else list)
.map(p => countryOf(p));
どう思いますか?
このtransform
関数は、標準の scala ライブラリのどこかに既に実装されていますか?