简体   繁体   English

Java Scala互操作性

[英]java scala interoperability

Let say you have a scala lib that needs to be used by your java programs but not only in the future. 假设您有一个scala库,您的Java程序需要使用它,而不仅仅是将来使用。

When it comes to collection and every goodies that you may have in scala. 当涉及到收藏以及scala中可能包含的所有好东西时。 Would you rather create some methods specific for java in your class, or somewhat in line with the single responsibility principle, you would create a bunch of static object that provide for the method that convert your object in there scala version using explicit conversion, asjava. 您宁愿在类中创建一些特定于Java的方法,还是在某种程度上符合单一职责原则,您将创建一堆静态对象,以提供使用显式转换asjava在scala版本中转换对象的方法。

If there was a way to convert asJava from within java that would be way easier, but i don't know if that package of explicit conversion can be used from within java. 如果有一种从java内转换asJava的方法会更容易,但是我不知道是否可以从java内使用该显式转换包。 I doubt as i feel that it use type class to augment the functionality. 我怀疑它使用类型类来增强功能。

Is there anything from java that could help. Java有什么可以帮助您的吗?

What is the best practice here. 最佳做法是什么?

Many thanks in advance. 提前谢谢了。

Calling Scala code from Java is usually much trickier than the other way around. 从Java调用Scala代码通常比其他方法复杂得多。 You can actually use asJava from Java too if you to reference the Scala standard library. 如果要引用Scala标准库,实际上也可以从Java使用asJava As for type classes, they are really just implicits that the compiler substitutes for you automatically. 对于类型类,它们实际上只是隐式的,编译器会自动将其替换为您。 In Java there are no implicits, obviously, so you need to pass the right instance yourself (which is somewhat cumbersome but doable). 显然,在Java中没有隐式函数,因此您需要自己传递正确的实例(这有点麻烦但可行)。 Here's an example of that (it's converting a Java map to a Scala one but it should work similarly the other way around): Convert java.util.HashMap to scala.collection.immutable.Map in java . 这是一个示例(它将Java映射转换为Scala,但反之亦然 ): 在java中将java.util.HashMap转换为scala.collection.immutable.Map

Personally I would say that you should introduce thin wrappers over the bits you want to expose to Java, which don't use any fancy Scala features like implicits, function objects (you can actually substitute those with Java 8 constructs) and such. 就我个人而言,我应该在要公开给Java的位上引入瘦包装器,这些包装器不使用任何花哨的Scala功能,例如隐式,函数对象(实际上可以用Java 8构造替换它们)等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM