Home > Back-end >  Filtering the results of zip in Scala 2
Filtering the results of zip in Scala 2

Time:08-06

In my scenario, there are three types: A, B and C with C being a subtype of A.

class C extends A
val a: Array[A] = ...
val b: Array[B] = ...

I've been trying to zip a and b first and then filter the results based on the type of the first element, but it seems I'm missing something here.

a.zip(b).filter(_: (A, B) => _._1.isInstanceOf[C]

This does not seem to work, since Scala completely disregards my type declaration for _ on the left side to type _ on the right side as Array[(A, B)].

Since I know isInstanceOf is not the scala way of doing things, I also considered using collect like this:

a.zip(b).collect{case x: (C, B) => x}

But this does not work, since scala does expect the types (A, B) here, rendering the type matching useless.

I'm used to Python programming, so maybe my approach is off here. Would appreciate any pointer in the right direction.

CodePudding user response:

_ is an anonymous parameter, you don't "declare" it, so it's either this:

a.zip(b).filter(_._1.isInstanceOf[C])

or this:

a.zip(b).filter { x: (A, B) => x._1.isInstanceOf[C] }

(note curly braces too)

Can also write it with a partial function syntax:

a.zip(b).filter { case (a,b) => a.isInstanceOf[C] }

or (better):

a.zip(b).filter { 
   case (_: C, _) => true
   case _ => false
}

or use collect as you suggested:

a.zip(b).collect { case x@(_: C, _) => x }

Personally, I prefer the last option over others.

  • Related