Scala, general purpose conversion function for all objects

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?

+1
source share
1 answer

Your transform is essentially an inverted form of a function application.

I do not know about the implementation in the standard library, but it is implemented in the Scalaz library as the |> operator, for example

 import scalaz.syntax.id._ users |> (list => if (onlyNice) list.filter(isNice) else list) 

Please note that since in this case the function is of type A => A and not A => B (that is, it is List[String] => List[String] ), you can use the identity function, for example,

 users |> (if (onlyNice) (_.filter(isNice)) else identity) 
+1
source

Source: https://habr.com/ru/post/1498713/


All Articles