什么是Scala对象的Java等价物? [英] What is the Java equivalent of a Scala object?

查看:127
本文介绍了什么是Scala对象的Java等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我们可以写

In Scala, we can write

object Foo { def bar = {} }

编译器如何实现?我可以从Java
调用 Foo.bar(); 但是新的Foo(); 来自Java给出错误找不到符号符号:构造函数Foo()

How is this implemented by the compiler? I am able to call Foo.bar(); from Java but new Foo(); from Java gives the error cannot find symbol symbol: constructor Foo()


  • 是否JVM本身支持单例吗?

  • 是否可以在Java中使用没有构造函数的类?

注意:这是代码输出 scalac -print

package <empty> {
  final class Foo extends java.lang.Object with ScalaObject {
    def bar(): Unit = ();
    def this(): object Foo = {
      Foo.super.this();
      ()
    }
  }
}


推荐答案

对单身人士的支持不在语言层面,但该语言提供了足够的设施来创建它们。

Support for singletons is not on a language level, but the language provides enough facilities to create them without any trouble.

考虑以下代码:

public class Singleton {
    private static final Singleton instance = new Singleton();

    // Private constructor prevents instantiation from other classes
    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

这是维基百科的一个例子,它解释了如何可以制作单身人士。实例保存在私有字段中,构造函数在类外部不可访问,该方法返回此单个实例。

This is an example from Wikipedia, which explains how a singleton can be made. An instance is kept in a private field, constructor is inaccessible outside the class, the method returns this single instance.

至于构造函数:每个默认情况下,class有一个所谓的默认构造函数,它不带参数,只调用超类的no-args构造函数。如果超类没有任何没有参数的可访问构造函数,则必须编写一个显式构造函数。

As for constructors: every class by default has a so-called default constructor which takes no arguments and simply calls the no-args constructor of the superclass. If the superclass doesn't have any accessible constructor without arguments, you will have to write an explicit constructor.

所以一个类必须有一个构造函数,但是你没有如果超类有一个no-args构造函数,则必须编写它。

So a class must have a constructor, but you don't have to write it if the superclass has a no-args constructor.

这篇关于什么是Scala对象的Java等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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