Search code examples
scalascala-2.8

Pass null to a method expects Long


I have a Scala method that takes 2 parameters:

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

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

test(null,x)

The result:

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

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

*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?

Any ideas!

Thanks.


Solution

  • 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.

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

    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.

    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.