Ber*_*ium 5 scala scala-java-interop
给定Scala中的服务:
class ScalaService {
def process1(s: Option[String], i: Option[Int]) {
println("1: " + s + ", " + i)
}
}
Run Code Online (Sandbox Code Playgroud)
这是从Java使用的:
public class Java {
public static void main(String[] args) {
ScalaService service = new ScalaService();
// This works, but it's confusing
{
scala.Option<String> so = scala.Option.apply("Hello");
scala.Option<Object> io = scala.Option.apply((Object) 10);
service.process1(so, io);
}
// Would be OK, but not really nice
{
scala.Option<Object> so = scala.Option.apply((Object) "Hello");
scala.Option<Object> io = scala.Option.apply((Object) 10);
service.process1(so, io); // Does not compile
}
// The preferred way
{
scala.Option<String> so = scala.Option.apply("Hello");
scala.Option<Integer> io = scala.Option.apply(10);
service.process1(so, io); // Does not compile
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想避免以不同的方式处理原始类型和非原始类型.
所以我尝试通过添加另一种方法来解决这个问题:
def process2(s: Option[String], i: Option[java.lang.Integer]) {
print("2: ")
process1(s, i.map(v => v.toInt))
}
Run Code Online (Sandbox Code Playgroud)
但这需要该方法的不同名称.从调用者的角度来看,这可能会让人感到困惑,还有其他可能吗?
我正在使用Scala 2.10.1和Java 1.6
我要测试的解决方案是使用 a DummyImplicit,因此我可以为 Scala 和 Java 方法使用相同的方法名称:
class ScalaService {
// To be called from Scala
def process(s: Option[String], i: Option[Int])(implicit d: DummyImplicit) {
println("1: " + s + ", " + i)
}
// To be called from Java
def process(s: Option[String], i: Option[java.lang.Integer]) {
print("2: ")
process(s, i.map(v => v.toInt))
}
Run Code Online (Sandbox Code Playgroud)
从 Scala 中使用如下:
object ScalaService extends App {
val s = new ScalaService()
s.process(Some("Hello"), Some(123))
}
Run Code Online (Sandbox Code Playgroud)
以及来自 Java 的:
public class Java {
public static void main(String[] args) {
ScalaService service = new ScalaService();
{
scala.Option<String> so = scala.Option.apply("Hello");
scala.Option<Integer> io = scala.Option.apply(10);
service.process(so, io);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4354 次 |
| 最近记录: |