Skip to content
This repository has been archived by the owner on Jan 25, 2018. It is now read-only.

Commit

Permalink
Add a filterByType method to TraversableLikes
Browse files Browse the repository at this point in the history
  • Loading branch information
cjllanwarne committed Aug 24, 2017
1 parent 2ee0bd8 commit 685d7e0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/main/scala/lenthall/collections/EnhancedCollections.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package lenthall.collections

import scala.collection.TraversableLike
import scala.collection.generic.CanBuildFrom
import scala.reflect.ClassTag

object EnhancedCollections {

/**
* After trying and failing to do this myself, I got this to work by copying the answer from here:
* https://stackoverflow.com/questions/29886246/scala-filter-by-type
*/
implicit class EnhancedTraversableLike[T2, Repr <: TraversableLike[T2, Repr], That](val traversable: TraversableLike[T2, Repr]) extends AnyVal {
/**
* Lets you filter a collection by type.
* eg.
* val xs: Set[Object]
* val strings = xs.filterByType[String]
*/
def filterByType[T : ClassTag](implicit bf: CanBuildFrom[Repr, T, That]): That = traversable.collect {
case t: T => t
}
}
}

22 changes: 22 additions & 0 deletions src/test/scala/lenthall/collections/EnhancedCollectionsSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package lenthall.collections

import org.scalatest.{FlatSpec, Matchers}
import lenthall.collections.EnhancedCollections._

class EnhancedCollectionsSpec extends FlatSpec with Matchers {
behavior of "EnhancedCollections"

it should "filter a List by type and return a List" in {
val objectList = List("hello", 3, None, "world")
val stringList: List[String] = objectList.filterByType[String]

stringList should be(List("hello", "world"))
}

it should "filter a Set by type and return a Set" in {
val objectSet = Set("hello", 3, None, "world")
val intSet: Set[Int] = objectSet.filterByType[Int]

intSet should be(Set(3))
}
}

0 comments on commit 685d7e0

Please sign in to comment.