【问题标题】:Extending Java Class with Scala Trait使用 Scala Trait 扩展 Java 类
【发布时间】:2013-04-17 20:52:15
【问题描述】:

我想定义一个类 ContextItem 作为 java 类 Predicate 的扩展,带有一个特征 Confidence

Confidence 是一个简单的 trait,它只是在其扩展的任何内容中添加一个 confidence 字段。

trait Confidence{
  def confidence:Double
}

我通过简单的说明来定义我的ContextItem 类:

class ContextItem extends Predicate with Confidence{}

但是尝试编译它会产生...

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{
             ^

这似乎是一个微不足道的例子,那么出了什么问题?

谓词(不是我的)看起来像:

/** 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);
    }
}

谓词及其任何祖先都没有实现置信度。

【问题讨论】:

  • 我们能看到Predicate 类吗?是否实现了confidence 方法?

标签: java scala inheritance traits


【解决方案1】:

我认为它列出了Predicate 的所有构造函数,并通知你你没有使用它们中的任何一个。默认是使用无参数构造函数,这里不存在。例如,调用(String) 超级构造函数的语法是

class ContextItem extends Predicate("something") with Confidence

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

另外,目前你的def confidence 是一个抽象方法,所以在你给它一个定义之前不会编译。如果您打算让 trait 添加一个可写的 confidence 字段,那么这就是您想要的:

var confidence: Double = 0.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多