Scala - null (?) as default value for named Int parameter
Asked Answered
A

3

8

I'd like to do in Scala something I would do in Java like this:

public void recv(String from) {
    recv(from, null);
}
public void recv(String from, Integer key) {
    /* if key defined do some preliminary work */
    /* do real work */
}

// case 1
recv("/x/y/z");
// case 2
recv("/x/y/z", 1);

In Scala I could do:

def recv(from: String,
         key: Int = null.asInstanceOf[Int]) {
    /* ... */
}

but it looks ugly. Or I could do:

def recv(from: String,
         key: Option[Int] = None) {
    /* ... */
}

but now call with key looks ugly:

// case 2
recv("/x/y/z", Some(1));

What's the proper Scala way? Thank you.

Ascomycete answered 23/1, 2012 at 13:35 Comment(3)
what about default value = -1 or 0?Unwarrantable
@Antoras That's possible, but not elegant (suppose that key can be any Int value).Ascomycete
"Some" will cease to look ugly once it saves you from a few dozen NullPointerExceptions :)Issy
G
17

The Option way is the Scala way. You can make the user code a little nicer by providing helper methods.

private def recv(from: String, key: Option[Int]) {
  /* ... */
}

def recv(from: String, key: Int) {
  recv(from, Some(key))
}

def recv(from: String) {
  recv(from, None)
}

null.asInstanceOf[Int] evaluates to 0 by the way.

Guardant answered 23/1, 2012 at 14:1 Comment(3)
Hmm, I would have just put the OP's /*do some preliminary work*/ in the two method overload, and then had that call the one method overload which does the /*do real work*/? Is the use of Option more idiomatic Scala?Zildjian
@TimGoodman, "then had that call the one method overload" -- with what argument?Guardant
With the string from that was passed to the two-method overloadZildjian
D
3

Option really does sound like the right solution to your problem - you really do want to have an "optional" Int.

If you're worried about callers having to use Some, why not:

def recv(from: String) {
  recv(from, None)
}

def recv(from: String, key: Int) {
  recv(from, Some(key))
}

def recv(from: String, key: Option[Int]) {
  ...
}
Decarburize answered 23/1, 2012 at 14:2 Comment(0)
R
2

The proper way is, of course, to use Option. If you have problems with how it looks, you can always resort to what you did in Java: use java.lang.Integer.

Rosenkranz answered 23/1, 2012 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.