Reputation: 2952
Apache Avro GenericRecord.get(colName) did the (dirty?) trick of returning an Object so it can return whatever type it wants. The Object contains other types: String, Int, Date, etc. The values can be null.
Example:
val one = genericRecord.get("hello") // "hello" resolves to an Int
val two = genericRecord.get("goodbye") // "goodbye" resolves to a String
"one" and "two" are of type Object, but they are "actually" an Int and String, respectively.
I'm trying to write an implicit class method to return an Option(<actual_type
>) with the result (to avoid dealing with the null case), so I can write
val myVal = genericRecord.getWithType("hello")
and have myVal be of type Option[Int].
Tried the following:
one match {
case i: Int => Option(i.asInstanceOf[Int])
case s: String => Option(s.toString)
}
But I get
error: pattern type is incompatible with expected type;
found : Int
required: Object
case x: Int =>
^
Matching on
one.getClass
doesn't work either. Is there a way to do this? If so, how?
Thanks!
Upvotes: 0
Views: 229
Reputation: 22085
When coming back from Java interoperability, Scala interprets Object
as AnyRef
. Since Int
is not a subtype of AnyRef
, the pattern matcher does not let you do a "stupid" thing.
You can force the interpretation as Any
simply by ascribing the result of get
with : Any
:
val one = genericRecord.get("hello"): Any
Upvotes: 1