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

15,028

Solution 1

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.

Solution 2

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]) {
  ...
}

Solution 3

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.

Share:
15,028
woky
Author by

woky

Updated on July 28, 2022

Comments

  • woky
    woky almost 2 years

    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.

  • Tim Goodman
    Tim Goodman over 10 years
    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?
  • missingfaktor
    missingfaktor over 10 years
    @TimGoodman, "then had that call the one method overload" -- with what argument?
  • Tim Goodman
    Tim Goodman over 10 years
    With the string from that was passed to the two-method overload