且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何从Java调用Scala单例方法?

更新时间:2023-11-13 14:15:04

我认为这间接涵盖了它:

I think this indirectly covers it:

伴随对象和Java静态
方法

Companion Objects and Java Static Methods

还有一件事要了解
伴侣对象。每当你定义
一个主要方法用作应用程序的入口
点时,Scala
要求你把它放在一个对象中。
但是,在撰写本文时,
主要方法无法在
伴随对象中定义。由于
生成代码中的
实现细节,JVM将找不到
main方法。此问题可能是在将来的版本中解决的
。现在,
你必须在
单例对象中定义任何main方法(即
非伴侣对象)[ScalaTips]。
考虑下面一个
简单Person类和伴随
对象的例子,它试图定义main。

There is one more thing to know about companion objects. Whenever you define a main method to use as the entry point for an application, Scala requires you to put it in an object. However, at the time of this writing, main methods cannot be defined in a companion object. Because of implementation details in the generated code, the JVM won’t find the main method. This issue may be resolved in a future release. For now, you must define any main method in a singleton object (i.e., a "non-companion" object) [ScalaTips]. Consider the following example of a simple Person class and companion object that attempts to define main.

如此处所示: http://programming-scala.labs.oreilly.com/ ch06.html

简而言之,因为你的Object是一个伴侣对象(有一个伴侣类),你不能像预期的那样调用它。正如你发现的那样,如果你摆脱了这个课程,那就可以了。

In short because your Object is a companion object (has a companion class) you can't call it like you expect. As you found if you get rid of the class it will work.