使用空参数从 Scala 调用 Java API [英] Calling Java API from Scala with null argument

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

问题描述

我有一些需要调用 Java API 的 Scala 代码

I have some Scala code that needs to call a Java API

Java API 接受可能为 null 的参数.当然,我的 Scala 使用 Option.

The Java API takes arguments that may be null. My Scala, of course, uses Option.

例如,假设我有一个 Java 对象构造函数 Foo(Integer),其中 Integer 可能是 null.我想给它一个 Scala bar: Option[Int].

For example, let's say I have a Java object constructor Foo(Integer) where the Integer may be null. I want to call it given a Scala bar: Option[Int].

我试过了

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._

val foo = Foo( bar.getOrElse(null) )

但是得到这个编译错误

Error:(335, 44) type mismatch;
  found   : Any
  required: Integer
  bar.getOrElse(null),

这样做的正确习语是什么?

What is the correct idiom for doing this?

推荐答案

我刚发布问题,就在相关列表中找到了答案(抱歉)

No sooner do I post the question, than I spot the answer in the related list (sorry)

解决办法

val foo = Foo(bar.getOrElse(null).asInstanceOf[java.lang.Integer])

有点笨重.有人有更好的吗?

Kind of clunky. Anyone have anything better?

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

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