Reputation: 3519
I am working with a Java library. This library has a bunch of collections for which I want to have implicit views in my Scala code. The Java library's object model follows a pattern like this:
(NarrowStreet | WideStreet) extends Street extends Road extends TwoNode
StreetList extends java.util.AbstractList< Street>
RoadList extends java.util.AbstractList< Road>
and so on. A StreetList
virtually behaves like a List<Street>
.
I need to use a method in this library which has the following signature:
List<StreetList> city.getStreets();
In Scala, I do the following to implicitly get to a Seq[Street]
collection:
implicit def twoNodeView[T <: java.util.AbstractList[_ <: TwoNode]](x : T): Seq[_ <: TwoNode] = for(i <- 0 until x.size()) yield x.get(i)
Now when I do
city.getStreets.asScala.flatten //.map, .filter, etc.
it gives me a Seq[TwoNode]
. I cast the objects when I use the collection in a map
or filter
function and I think I am safe since I am 100% sure that this object is a Seq[Street]
and not really a Seq[TwoNode]
.
Questions:
Are there any fail scenarios the way I am implementing the implicit view?
Can this be improved or is there a better way to achieve the same result and avoid casting?
Upvotes: 0
Views: 75
Reputation: 170745
You don't need to define your own implicits for this. Just use
city.getStreets.asScala.map(_.asScala)
to get the nested Buffer[Buffer[Street]]
and then .flatten
it into Seq[Street]
if you want.
Upvotes: 2