Mix covariance between Kotlin and Scala

43 Views Asked by At

I have a Kotlin class

class Result<out ResultType>(val value: ResultType, val msg:String?)

which I use in Scala with no problem, until I tried to write something like this

def processResult(result: Result[AnyRef]) = ...

processResult( new Result[Int](4) )

last line doesn't compile because

type mismatch;
   found   : Result[Int]
   required: Result[AnyRef]

Now, I expect that Scala will not manage to understand Kotlin's 'out' definition, but I don't see anyway to write processResult() in a way that will not force me to write explicit casts every time.

How do I do it?

1

There are 1 best solutions below

3
Gaël J On

You have two issues here.

1/ In Scala, Int is not a subtype of AnyRef (reference types) but of AnyVal (all values types). Any being the supertype of both.

You'd have the same error in pure Scala code:

case class Result[+ResultType](value: ResultType)

def processResult(result: Result[AnyRef]) = ???

processResult(new Result[Int](4))

Using Any solves this first issue. This might not be encouraged though as you kinda lose any information about the underlying type.

You could rather add the type to the method itself:

def processResult[T](result: Result[T]) = ???

It depends on what you expect to do.

2/ Indeed there's no interop between Kotlin out and Scala +/-. That I don't think there's an easy way around it unfortunately.

Edit: as suggested by Luis in the comments, a wrapper class + using .asInstanceOf in the wrapper class could be a solution.