Best FP Idioms for AnyVals in Collections

I have a display function defined as such:

def foo(x:Int) = if (x>2) x*2

      

the type signature of this method Int => AnyVal

. Now if I list this function over a list of integers:

scala> List(-1,3,-4,0,5).map(foo)
res0: List[AnyVal] = List((), 6, (), (), 10)

      

I need a way to filter Unit

out Int

like this:

scala> res0.filter(_.isInstanceOf[Int]).map(_.asInstanceOf[Int])
res1: List[Int] = List(6, 10)

      

Everything seems to be succinct until I do a filter map on res0

to extract the values ​​that I care about. I could use matchers or if-else in foo

to ensure that I always return Int

, but I would still need to filter out unnecessary values ​​resulting from the map operation.

Can anyone experienced Scala developers reading this give some idea of ​​what's good or bad in this regard, especially when my collection grows (for example, maybe this collection is Spark distributed RDD

)? Are there more idiomatic ways to do this functionally?

+3


source to share


1 answer


In this case, I suggest you use a collection with PartialFunction if you need to discard all ints that are less than 2 in size

  val foo: PartialFunction[Int, Int] = {
    case x if x > 2 => x*2
  }

  println(List(-1,3,-4,0,5).collect(foo))

      

Your original foo has type Int => AnyVal because scalac converts it to something like



def foo(x: Int) = if (x > 2) x*2 else () // () === Unit

      

and the general type super for Int and Unit is AnyVal

+7


source







All Articles