你如何从Java调用Scala单例方法? [英] How do you call a Scala singleton method from Java?

查看:735
本文介绍了你如何从Java调用Scala单例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些Scala代码注入我现有的Java应用程序中。 (所以说,我想要更多的乐趣)。

I'm trying to inject some Scala code into my existing Java app. (So, being said, I want some more fun).

我在Scala中创建一个单例东西

I create a singleton stuff in Scala

ScalaPower.scala

    package org.fun
    class ScalaPower
    object ScalaPower{
      def showMyPower(time:Int) = {
        (0 to time-1).mkString(", ")
      }
    }

现在,在OldJava.java中

Now, inside OldJava.java

class OldJava {
  public void demo(){
    System.out.println(?)
  }
}

我应该填写,以便Java调用showMyPower方法?
我试过 org.fun.ScalaPower.showMyPower(10) org.fun.ScalaPower.getInstance()。showMyPower(10 )但没有工作。

What should I fill in ? so that Java will call the showMyPower method? I tried both org.fun.ScalaPower.showMyPower(10) and org.fun.ScalaPower.getInstance().showMyPower(10) but none work.

(使用Jad反编译类文件只显示废话代码。)

(Decompile the class file using Jad show me nothing but nonsense code.)

编辑
我删除类ScalaPower 声明,scala按预期生成静态方法。 (调用 org.fun.ScalaPower.showMyPower(10)正常工作)。

Edit I remove the class ScalaPower declaration and scala produce the static method as expected. (call to org.fun.ScalaPower.showMyPower(10) just works).

不知道这是不是一个bug是否在scala编译器中

Wonder if it's a bug in scala compiler or not

推荐答案

我认为这间接涵盖了它:

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.

这篇关于你如何从Java调用Scala单例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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