This repository has been archived by the owner on Jan 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a
filterByType
method to TraversableLikes
- Loading branch information
1 parent
2ee0bd8
commit 685d7e0
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
25 changes: 25 additions & 0 deletions
25
src/main/scala/lenthall/collections/EnhancedCollections.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
22
src/test/scala/lenthall/collections/EnhancedCollectionsSpec.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
} | ||
} |