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

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

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(", ")

}

}

Now, inside OldJava.java

class OldJava {

public void demo(){

System.out.println(?)

}

}

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.

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

Edit

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

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

解决方案

I think this indirectly covers it:

Companion Objects and Java Static

Methods

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值