Scala/Java互操作性:如何处理包含Int/Long(原始类型)的选项? [英] Scala/Java interoperability: How to deal with options containing Int/Long (primitive types)?

查看:212
本文介绍了Scala/Java互操作性:如何处理包含Int/Long(原始类型)的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中提供服务:

Given a service in Scala:

class ScalaService {
  def process1(s: Option[String], i: Option[Int]) {
    println("1: " + s + ", " + i)
  }
}

要在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
        }

    }
}

我想避免以不同的方式对待原始类型和非原始类型.

I'd like to avoid to treat primitive and non-primitive types in a different way.

因此,我尝试通过添加另一种方法来解决此问题:

So I tried to get around this by adding another method:

def process2(s: Option[String], i: Option[java.lang.Integer]) {
  print("2: ")
  process1(s, i.map(v => v.toInt))
}

,但这要求该方法使用不同的名称. 从调用者的角度来看这可能会造成混淆,是否还有其他可能性?

but this requires a different name for the method. As this could be confusing from the caller's perspective, are there any other possibilities?

我正在使用Scala 2.10.1和Java 1.6

I'm using Scala 2.10.1, and Java 1.6

推荐答案

我要测试的解决方案是使用DummyImplicit,因此对于Scala和Java方法,我可以使用相同的方法名称:

The solution I am going to test is to use a DummyImplicit, so I can have the same method name for both the Scala and the Java method:

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))
  }

可以像这样在Scala中使用:

to be used from Scala like this:

object ScalaService extends App {
  val s = new ScalaService()
  s.process(Some("Hello"), Some(123))
}

和来自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);
        }
    }

}

这篇关于Scala/Java互操作性:如何处理包含Int/Long(原始类型)的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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