I have created a project that uses scala that has some abstract classes definitions such as:
abstract class A(n: String) {
require(n!= null)
val name = n
var inputs: List[Input[_]]
var outputs: List[Output[_]]
}
abstract class B(n: String) extends A(n){
def act
def isValid : Boolean
def getCs : List[C[_]]
}
abstract class C[Type]{
var value: Type
}
Now I want to use that project in Java. I have imported scala lib in a new project and added scala project in the build path. I am using eclipse.
However, when I try to do this:
public class CoolClass extends B {
public CoolClass(){ }
}
EDIT:
I have some problems using this in Java that raised me some doubts. Let me enumerate them:
getCs
so it provides an interface with List<C>
instead of List<C<?>>
?I'm just assuming, that you implemented all the methods you define in you class B
also in your java class CoolClass
. What is missing here is the call to B
's constructor, as the error message says.
class CoolClass extends B {
public CoolClass() {
super("");
}
// methods implementations
}
There is no default constructor defined on your class B
, so you have to explicitly call the one that is defined, which is B(n: String)
.
edit:
1: You can use anything you want on both sides. Though the method names may be different in some special cases like anything that includes special chars in scala.
2: They are recognized, though they are not fields, but methods in the java code. You can access them with this.inputs()
and this.outputs()
3: Try def getCs[C]: List[C]
def getCs : List[C[_]]
will not compile, because C
is not known. You are talking of 2 fields in the A class, could you please edit your original post accordingly - drexin 2012-04-06 10:33
2 - I couldn't acess the fields of a class with this.field().
Maybe I should declare a method for each field?
3 - Almost worked. However it returns a <Object>
instead of <C>
I belive scala doesn't integrate that well with Java. Maybe I do the basic structure with Java and then I add some layers to my work with scala. Probly with classes that aren't going to be extended in Java and don't use Generic this works better - Tiago Almeida 2012-04-06 12:26
Your B class is essentially as you describe:
public abstract class B extends A {
public B(String n) {
super(n);
}
public abstract void act()
public abstract boolean isValid();
public abstract List<C<?>> getCs();
}
Your CoolClass is missing the explicit super call in the constructor:
public CoolClass extends B {
public CoolClass() { // override ctor with no string parameter
super("defaultStringValue");
}
public CoolClass(String n) { // override ctor with no string parameter
super(n);
}
…
As you can see Scala makes it so trivial to declare and call constructors we forget how much boilerplate they add in Java.