Why can't `(T) this` from Java work in scala?

Given these Java class definitions:

class Base { int value; public <T extends Base> T self() { return (T) this; } } class Derived extends Base {} 

this java code compiles fine:

 new Derived().self(); 

but this Scala code does not run:

 (new Derived).self(); // runtime error 

Runtime Error:

 java.lang.ClassCastException: Derived cannot be cast to scala.runtime.Nothing$ 

Why does this not work, and how to fix it?

+4
source share
2 answers

In scala, this method looks like self[T <: Base](): T In (new Derived).self() you did not specify T This means the most specific type is Nothing .

So, (new Derived).self() is actually (new Derived).self[Nothing]() .

You can try (new Derived).self[Derived]() or val d: Derived = (new Derived).self() .

+4
source

I think you are writing the wrong code. I tested in JDK 1.6.

 new Derived().self(); (new Derived()).self(); 

everything is good.

But (new Derived).self(); gives a compilation error!

0
source

Source: https://habr.com/ru/post/1479462/


All Articles