Cannot indirectly pour A [T] into AT, where A [T] extends AT

The problem is with the integration between Java and Scala. I simplified it a bit to make things clearer.

I have two classes written in Java:

class A<T>{} class AT extends A<Boolean> {} 

In Java, I have a method that uses classes as follows:

 public A<Boolean> a(){ return new AT(); } 

I would like to do the same in Scala. But the code below does not compile.

 def a(): A[Boolean] = { return new AT(); } 

The report says: "Type of mismatch: found: org.rarry.sample.AT required: org.rarry.sample.A [Boolean]"

Can someone explain why this is so and how to do it?

+6
source share
1 answer

To understand the reason why your code does not compile, first notice that Java uses java.lang.Boolean for a buffered type with a buffer, and Scala uses scala.Boolean . In most cases, when you want to use one of them, and the method returns the other (or the method argument requires the other), an implicit conversion will be performed and the correct type will be used.

The a method you wrote in Scala really returns A[java.lang.Boolean] . Since there is no implicit conversion between A[java.lang.Boolean] and A[scala.Boolean] , it will not automatically return A[scala.Boolean] in this case.

To make sure this is the case, we see that this method compiles without problems:

 def a: A[java.lang.Boolean] = new AT() 

To repeat this point, because we do not have an implicit conversion, this also will not work (you will see how this can be eliminated below):

 val instanceOfA: A[Boolean] = a def a = new AT() // Error: AT doesn't conform to A[Boolean] 

To fix this, you can implicitly convert to the desired type by doing it:

 implicit def toScalaABoolean(a: A[java.lang.Boolean]): A[Boolean] = a.asInstanceOf[A[Boolean]] 

You don’t even have to declare the return type of method a :

 implicit def toDifferentBoolean(a: A[java.lang.Boolean]): A[Boolean] = a.asInstanceOf[A[Boolean]] val instanceOfA: A[Boolean] = a def a = new AT() 
+5
source

All Articles