在 Scala 程序中混合 Java 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6357890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mixing Java code in Scala program?
提问by ace
Is this allowed in Scala code:
这在 Scala 代码中是否允许:
DomNode node = node.getFirstChild()
where DomNode is Java type from external java library and getFirstChild() is defined on DomNode type.
其中 DomNode 是来自外部 Java 库的 Java 类型,而 getFirstChild() 是在 DomNode 类型上定义的。
I am porting existing java program to scala and it would be very convenient if I leave original java declerations as is to minimize porting efforts.
我正在将现有的 Java 程序移植到 Scala,如果我保留原始的 Java 声明以尽量减少移植工作,那将非常方便。
回答by Jesper
You can use Java classes in a Scala program, but you would ofcourse have to use Scala syntax:
您可以在 Scala 程序中使用 Java 类,但您当然必须使用 Scala 语法:
val node: DomNode = node.getFirstChild()
You cannot use Java syntax in the form Type variableName.
您不能在表单中使用 Java 语法Type variableName。
edit(thanks to ericacm) - You can also just specify
编辑(感谢 ericacm) - 您也可以指定
val node = node.getFirstChild()
so you don't have to specify the type of nodeexplicitly; you can let Scala infer the type.
所以你不必node明确指定类型;你可以让 Scala 推断类型。
回答by agilesteel
IntelliJ IDEA can translate from Java to Scala for you. If you paste Java code into a ".scala" file IntelliJ IDEA notices it and asks you if you would like to try an automatic conversion. You might wanna check it out.
IntelliJ IDEA 可以为您从 Java 转换为 Scala。如果您将 Java 代码粘贴到“.scala”文件中,IntelliJ IDEA 会注意到它并询问您是否要尝试自动转换。你可能想看看。
PS
聚苯乙烯
I never tried it out myself...
我自己从来没有试过...

