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.

3
  • what about default value = -1 or 0? Commented Jan 23, 2012 at 13:40
  • @Antoras That's possible, but not elegant (suppose that key can be any Int value). Commented Jan 23, 2012 at 13:43
  • 3
    "Some" will cease to look ugly once it saves you from a few dozen NullPointerExceptions :) Commented Jan 23, 2012 at 14:09

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@TimGoodman, "then had that call the one method overload" -- with what argument?
With the string from that was passed to the two-method overload
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]) {
  ...
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.