I would like to have something like the following:
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));
that is, I want to apply the isNice filter only if onlyNice==true . I could do it like this:
val result = users .filter(_.contains("john") .map(._toUpperCase) .filter(p => !onlyNice || isNice) .map(p => countryOf(p));
but this will decrease performance because we are browsing the entire list, even if Nice is false.
we could do the following:
val tmp = users .filter(_.contains("john") .map(._toUpperCase) val tmp2 = if (onlyNice) tmp.filter(isNice) else tmp val result = tmp2. .map(p => countryOf(p));
but it's harder to read.
This seems like a good generalized solution for me:
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));
what do you think?
Is this transform function already implemented in the scala standard library somewhere?
source share