Search code examples
scalahector

hector scala type mismatch


What could be wrong?

val is = IntegerSerializer.get
mutator.addInsertion(deviceId, COLUMN_FAMILY_CARSTATUS, createColumn("mileage", 111, ss, is))}


ModelOperation.scala:96: error: type mismatch;
[INFO]  found   : me.prettyprint.cassandra.serializers.IntegerSerializer
[INFO]  required: me.prettyprint.hector.api.Serializer[Any]
[INFO] Note: java.lang.Integer <: Any (and me.prettyprint.cassandra.serializers.IntegerSerializer <: me.prettyprint.cassandra.serializers.AbstractSerializer[java.lang.Integer]), but Java-defined trait Serializer is invariant in type T.
[INFO] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[INFO]      mutator.addInsertion(deviceId, COLUMN_FAMILY_CARSTATUS, createColumn("mileage", 111, ss, is))}

Solution

  • The error is saying that createColumn requires a serializer of type Serializer[Any], but you're passing one of type Serializer[Integer]. This would only work if Serializer were covariant in its type parameter (i.e., defined as Serializer[+T]). But instead, Serializer comes from Java, where covariance works differently.

    The type Serializer[Integer] can be safely cast to Serializer[_ <: Any], so the Scala compiler is suggesting that maybe createColumn should have been written to expect that less specific wildcard type instead.

    If you can't modify createColumn, then a last resort is to use the "type system escape hatch" asInstanceOf to cast to the expected type:

    val is = IntegerSerializer.get.asInstanceOf[Serializer[Any]] // defeats type system
    mutator.addInsertion(... is ...)