0

Is it possible to make a method in a Scala class extending class A being called through another class B extending class A and implementing the trait?

public class A {
    public int foo(int someData) {
        return -1;
    }
}

If I would extend the trait with a Scala class the method from the trait would be called. In java it doesn't.

trait T extends A {
    override def foo(int: someData) = {
        if data < 10 {
            return data * 2
        } else {
            return 0
        }
    }
}

This is the class I am calling foo() from:

public class B extends A implements T {}

This is supposed to print 44 not -1

public class Main {
    B b = new B();
    System.out.println(b.foo(22));
}
Busti
  • 5,492
  • 2
  • 21
  • 34

1 Answers1

0

This works:

scala> trait A {
     | def foo(someData:Int) = -1
     | }
defined trait A

scala> trait T extends A {
     | override def foo(someData:Int) = if (someData<10) someData*2 else 0
     | }
defined trait T

scala> class B extends T
defined class B

scala> val b = new B
b: B = B@4e009c5e

scala> b.foo(3)
res4: Int = 6

By the way, b.foo(22) would print 0, not 44, according to your own definition.

UPDATE: just realized that you meant Java -> Scala -> Java inheritance. My answer was related to Scala only. In principle the same should apply to Java (more about it in this answer: Using Scala traits with implemented methods in Java and also here: http://lampwww.epfl.ch/~michelou/scala/using-scala-from-java.html ) - the traits with method implementations are supposed to be translated into Java as interfaces and the traits with method implementations as abstract classes.

Did you try to create your B class in java as:

public class B implements T {}

?

Community
  • 1
  • 1
Ashalynd
  • 12,363
  • 2
  • 34
  • 37