Reputation: 3942
I am using a Java library which returns an object of type Object
. Now I want to pattern match and get the appropriate type. I expect it to be a Java Map. So, I tried using this:
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scala.collection.JavaConverters._
val any: Any = new java.util.HashMap[Object, Object]
Option(any).flatMap {
case x: java.util.Map[_, _] => Some(x.asScala.toMap)
case x: Map[_, _] => Some(x)
case _ => None
}
// Exiting paste mode, now interpreting.
<console>:17: error: no type parameters for method flatMap: (f: Any => Option[B])Option[B] exist so that it can be applied to arguments (Any => Option[scala.collection.immutable.Map[_,Any]] forSome { type _ })
--- because ---
argument expression's type is not compatible with formal parameter type;
found : Any => Option[scala.collection.immutable.Map[_,Any]] forSome { type _ }
required: Any => Option[?B]
Option(any).flatMap {
^
<console>:17: error: type mismatch;
found : Any => Option[scala.collection.immutable.Map[_,Any]] forSome { type _ }
required: Any => Option[B]
Option(any).flatMap {
^
Not sure what I am doing wrong here.
Upvotes: 1
Views: 913
Reputation: 11587
The below works. The compiler doesn't have the enough information to derive the type here since we are using existential types for our Maps in the pattern matching. This is because unlike Java Map
is not a type in scala but Map[T,U]
is
Option(any).flatMap[Any]({
case x: java.util.Map[_, _] => Some(x.asScala.toMap)
case x: Map[_, _] => Some(x)
case _ => None
})
If we dont use existential type as shown below, we would be able to use the flatMap without the explicit type parameter specified
scala> Option(any).flatMap({
| case x: java.util.Map[Int, Int] @unchecked => Some(x.asScala.toMap) // using Int as example to create a fully qualified type of Map
| case x: Map[Int, Int] @unchecked => Some(x) // using Int as example to create a fully qualified type of Map
| case _ => None
| })
res5: Option[scala.collection.immutable.Map[Int,Int]] = Some(Map())
Upvotes: 1