在Scala中使用Java库 [英] Using Java libraries in Scala

查看:396
本文介绍了在Scala中使用Java库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Scala的新手。到目前为止我只能编写基本代码,但我想更具体地开始使用它,而不仅仅是学习理论。

I am a new to Scala. I am only able to write basic code thus far, but I want to start using it more concretely, rather than just learning theory.

假设我有以下Java代码在 HelloWorld.java

Lets say I have the following Java code in HelloWorld.java:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}

等效的Scala代码是什么? ?

What would the equivalent Scala code be?

推荐答案

在你的例子中,你只需要一个main,而不是你必须从其他地方调用的函数。但是我们说你确实有一个像

In your example, you just have a main, not a function you would necessarily call from somewhere else. But let's said you did have a function like

package com.example.hello;

public class HelloWorld {
  public static void sayHello() {
    System.out.println("Hello, world!");
  }
}

(我还为你的例子添加了一个包,for完整性)。然后在你的Scala代码中,你可以这样做:

(I also added a package for your example, for completeness). Then in your Scala code, you could do:

import com.example.hello._

(0 until 10).foreach {
  HelloWorld.sayHello()
}

在Scala中使用Java函数10次打招呼。 import 中的 ._ 导入包的所有成员,或者只能 import com.example.hello.HelloWorld 。您甚至可以使用 import com.example.hello.HelloWorld.sayHello 导入方法本身,这样您就不需要引用 HelloWorld 代码中的对象。

to say hello using the Java function 10 times in Scala. The ._ in the import imports all members of the package, or alternatively you could just import com.example.hello.HelloWorld. You could even import the method itself with import com.example.hello.HelloWorld.sayHello so that you don't need to reference the HelloWorld object in your code.

两种语言都编译成JVM字节码,因此从Scala调用Java代码非常简单,尽管从Java调用Scala可能比较棘手如果涉及隐含参数。

Both languages compile into JVM bytecode, so calling Java code from Scala is very simple, although calling Scala from Java can be trickier if there are are implicit parameters involved.

这篇关于在Scala中使用Java库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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