Scala - null (?) As the default value for the specified Int parameter

I would like to do in Scala what I would do in Java, for example:

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 looks ugly. Or I could do:

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

but now the call with red looks ugly:

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

What is the correct way to Scala? Thanks.

+6
source share
3 answers

The Option method is the Scala path. You can make the user code a little better 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] incidentally refers to 0 .

+15
source

Option really sounds like the right solution to your problem - you really want to have an β€œoptional” Int .

If you are worried that callers should 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]) { ... } 
+3
source

The correct way, of course, is 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 .

+2
source

Source: https://habr.com/ru/post/906658/


All Articles