Search code examples
javascalathrift

Type mismatch in scala with wildcards


I have a piece of code from java that i am trying to implement in scala.

java code, works fine.

protected byte[] serialize(final TBase<?, ?> base) {
    try {
        return new TSerializer(new TCompactProtocol.Factory()).serialize(base);
        } catch (final TException e) {
        throw new RuntimeException(e);
      }
}

scala code i am tyring to implement.

def serialize(base: TBase[_,_]): Array[Byte]={
try{
  return new TSerializer(new TCompactProtocol.Factory()).serialize(base)
}catch {
  case ex: TException => {
    throw new RuntimeException(ex.getMessage())
  }
}

}

The compiler isnt giving me an error of "type mismatch; found : org.apache.thrift.TBase[_$1,_$2] where type _$2, type _$1 required: org.apache.thrift.TBase[_ <: org.apache.thrift.TBase[_, _], _ <: org.apache.thrift.TFieldIdEnum]"

I looked around a lot and one of the suggestions was to use and some and none type. But not sure it is the right thing to do. Can someone help me with this.


Solution

  • Without further information this answer is only a guess based on the error:

    type mismatch; 
    found : TBase[_$1,_$2] where type _$2, type _$1
    required: TBase[_ <: TBase[_, _], _ <: TFieldIdEnum]
    

    Constraining the type arguments as the error message suggested may fix the problem:

     def serialize(base: TBase[_ <: TBase[_,_] ,_ <: TFieldIdEnum])
    

    It's hard to tell why this would be case, without seeing the signatures of the serialize methods and the TBase class. I can only speculate that the java wildcards brings the constraint already defined somewhere else, while the scala existencials doesn't, requiring that you state than explicitly.

    Also, don't use the return keyword. It doesn't do what you think it does.