将 null 传递给需要 Long 的方法 [英] Pass null to a method expects Long

查看:65
本文介绍了将 null 传递给需要 Long 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 2 个参数的 Scala 方法:

I have a Scala method that takes 2 parameters:

def test(x:Long,y:Int){}

在某些情况下,我需要传递 null 而不是 long ...类似的东西:

On some occasion I need to pass null instead of long ... something like that:

test(null,x)

结果:

scala> test(null,2) :7: 错误:类型不匹配;成立 :需要空(空):长测试(空,2)

scala> test(null,2) :7: error: type mismatch; found : Null(null) required: Long test(null,2)

为什么我需要传递null?实际上,出于某种原因,我无法传递任何默认值.因此,我需要这样一个空值.

Why do I need to pass null? Actually ,for some reason,I can't pass any default values. Thus, I need such a null.

*注意:*我知道解决方案是将其设为 Option.但是,假设我无法控制此方法签名,我可以做任何解决吗?

*Note:*I know that the solution would be making it Option. However let's say I have no control over this method signature,can I do any work around?

任何想法!

谢谢.

推荐答案

既然不能改签名,考虑一下的错误思考 Option[Foo] 是表达缺失函数参数的唯一/最自然的方式.

Since you can't change the signature, consider the mistake of Thinking Option[Foo] is the only/most natural way to express a missing function argument.

如果你的函数的参数是一个下限,那么 Long.MinValue 可能是一个自然的默认值.

If the param to your function is a lower bound, then Long.MinValue might be a natural default.

如果通过出于某种原因,我无法传递任何默认值"(无论这可能意味着什么),您的意思是您无法向签名添加默认值,并且您将采用另一个答案中建议的路线调整方法,您不妨在转发之前将 f(a,b) 更改为 g(b, a=Long.MinValue) 或其他任何内容.

If by "for some reason,I can't pass any default values" (whatever that could possibly mean) you mean you can't add defaults to the signature, and you're going the route suggested in another answer of adapting the method, you might as well change f(a,b) to g(b, a=Long.MinValue) or whatever before forwarding.

与其让您的适配器方法的客户端调用 g(b, None),不如让它们调用 g(b).无论如何,您不会将 Option 传递给基础 f(a,b).

Instead of making clients of your adaptor method call g(b, None), let them call g(b). You're not passing the Option to the underlying f(a,b) anyway.

这篇关于将 null 传递给需要 Long 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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