简体   繁体   English

使用Scala Trait扩展Java类

[英]Extending Java Class with Scala Trait

I would like to define a class ContextItem as the extension of java class Predicate with a trait Confidence . 我想将一个类ContextItem定义为具有特征Confidence度的java类Predicate的扩展。

Confidence is a simple trait which simply adds a confidence field to whatever it extends. 信心是一个简单的特征,它只是为其扩展的内容添加一个置信区域。

trait Confidence{
  def confidence:Double
}

I am defining my ContextItem class by simply stating: 我只是通过声明来定义我的ContextItem类:

class ContextItem extends Predicate with Confidence{}

But attempting to compile this yields... 但是试图编译它会产生......

com/slug/berds/Berds.scala:11: error: overloaded method constructor Predicate with     alternatives:
  (java.lang.String,<repeated...>[java.lang.String])com.Predicate <and>
  (java.lang.String,<repeated...>[com.Symbol])com.Predicate <and>
  (java.lang.String,java.util.ArrayList[com.Symbol])com.Predicate <and>
  (com.Predicate)com.Predicate <and>
  (com.Term)com.Predicate <and>
  (java.lang.String)com.Predicate
 cannot be applied to ()
class ContextItem(pred:Predicate) extends Predicate with Confidence{
             ^

This seems like a trivial example, so what's going wrong? 这似乎是一个微不足道的例子,所以出了什么问题?

Predicate (which is not mine) looks like: 谓词(不是我的)看起来像:

/** Representation of predicate logical form. */
public class Predicate extends Term implements Serializable {
    public Predicate(String n) {
        super(n);
    }
    public Predicate(Term t) {
        super(t);
    }
    public Predicate(Predicate p) {
        super((Term)p);
    }
    public Predicate(String n, ArrayList<Symbol> a) {
        super(n, a);
    }
    public Predicate(String n, Symbol... a) {
        super(n, a);
    }
    public Predicate(String n, String... a) {
        super(n, a);
    }
    @Override
    public Predicate copy() {
        return new Predicate(this);
    }
}

Neither Predicate nor any of its ancestors implements confidence. 谓词或其任何祖先都没有实现信心。

I think it is listing all the constructors of Predicate , and informing you that you're not using any of them. 我认为它列出了Predicate所有构造函数,并通知您没有使用它们中的任何一个。 The default is to use a parameterless constructor, which doesn't exist here. 默认设置是使用无参数构造函数,此处不存在。 The syntax to call, for example, the (String) super-constructor, would be 调用的语法,例如, (String)超级构造函数,将是

class ContextItem extends Predicate("something") with Confidence

or 要么

class ContextItem(str: String) extends Predicate(str) with Confidence

Also, at the moment your def confidence is an abstract method, so won't compile until you give it a definition. 此外,目前你的def confidence是一个抽象方法,所以在你给它定义之前不会编译。 If you intended the trait to add a writable confidence field then this is what you want instead: 如果您希望该特征添加可写的confidence区域,那么这就是您想要的:

var confidence: Double = 0.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM