Scala无法解析继承的Java接口常量成员 [英] Scala can not resolve inherited Java interface constant members

查看:130
本文介绍了Scala无法解析继承的Java接口常量成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的类层次结构:

Class hierarchy in Java:

接口:集群分类

Class Kluster 层次结构如下所示

Class Kluster hierarchy is show below

Cluster  <- ,
            +-- Kluster
Classify <- '

文件: oop / Cluster.java

package oop;

public interface Cluster {
    public String HELLO = "hello";
}

文件: oop / Kluster.java

package oop;

interface Classify {
    public String GOODBYE = "good bye";
}

public class Kluster implements Cluster, Classify {

}

文件: oop / KlusterMain.java

package oop;

public class KlusterMain {
    public static void main(String[] args) {
        System.out.println(Kluster.HELLO);
        System.out.println(Kluster.GOODBYE);
    }
}

直到现在一切都按预期工作。我可以打印HELLO和GOODBYE常量。

Till now everything works as expected. I can print HELLO and GOODBYE constants.

现在当我尝试从Scala编译器访问它们时,它会出错。

Now when I try to access them from Scala compiler, it gives error.

文件: oop / cluster.scala

package oop

object cluster {
  def main(args: Array[String]) {
    val k = new Kluster
    println(Cluster.HELLO)
    println(Classify.GOODBYE)
    println(Kluster.HELLO) // <- this is the problematic line
  }
}

错误:

Scala Problem
value HELLO is not a member of object oop.Kluster
/scala-snippets/src/main/scala/oop/cluster.scala
line 8

为什么Scala不能解析 Kluster 对象同时实现 Cluster Classify 接口的层次结构?

Why can't Scala resolve the hierarchy that Kluster object implements both Cluster and Classify interfaces ?

推荐答案

你知道将常量放入接口以在实现类中使用它们是错误的认可我,不是吗?在Java中,您使用带有私有构造函数的 final 类,并使用 import static 来缩短常量名称(如果需要)。在Scala中,您使用 object 和导入。但是Scala没有静态字段的概念 - 它有对象而不是正确地参与继承。使用适当的面向对象系统将Java中的静态字段统一是不可能的,因此在Scala中,您不能使用子类中的静态成员(字段和方法)。

You do know that putting constants into interfaces to use them in implementing classes is bad approach, don't you? In Java you use final class with private constructor and use import static to shorten constant names, if needed. In Scala you use objects and imports. But Scala does not have notion of static fields - it has objects instead which participate in inheritance properly. It was impossible to unify static fields from Java with proper object-oriented system, so in Scala you can't use static members (fields and methods) from subclasses.

请参阅还此处

这篇关于Scala无法解析继承的Java接口常量成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆