Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 959
woky Avatar asked Jan 23 '12 13:01

woky


People also ask

Can int be null in Scala?

The explication of these empty values are as follows: null: The reference types such as Objects, and Strings can be nulland the value types such as Int, Double, Long, etc, cannot be null, the null in Scala is analogous to the null in Java.

How do I set default value in Scala?

You can assign a default value for a parameter using an equal to symbol. I gave a default value for the first parameter. If the caller doesn't pass any value for the first parameter, Scala will take the default value as println. That's it.

How do you handle null values in Scala?

In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.

Why should null be avoided in Scala?

We must try to avoid using null while initializing variables if there's an empty value of the variable's type available, such as Nil. Also, it's advisable to use Option types for functions that may return an empty result, instead of returning a null reference.


2 Answers

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.

like image 66
missingfaktor Avatar answered Oct 18 '22 14:10

missingfaktor


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]) {
  ...
}
like image 24
Paul Butcher Avatar answered Oct 18 '22 15:10

Paul Butcher