Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

When to use the equals sign in a Scala method declaration?

With equals sign:

object HelloWorld {
  def main(args: Array[String]) = {
    println("Hello!")
  }
}

Without equals sign:

object HelloWorld {
  def main(args: Array[String]) {
    println("Hello!")
  }
}

Both of the above programs execute the same way. In the blog post Things I do not like in Scala I read that when the equals sign are missing, the method will return Unit (same as Java's void), so methods that return a value must use the equals sign. But methods that don't return a value can be written either way.

What is the best practice for using the equals sign in Scala methods that don't return a value?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I actually disagree pretty strongly with Daniel. I think the non-equal syntax should never be used. If your method is being exposed as an API and you're worried about accidentally returning the wrong type, add an explicit type annotation:

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello!")
    123
  }
}

The non-equal syntax is shorter and might look "cleaner", but I think it just adds the possibility of confusion. I have sometimes forgotten to add an equal sign and believed my method was returning a value when actually it was returning Unit. Because the non-equal and equal-with-inferred-type syntaxes are so visually similar, it's easy to miss this problem.

Even though it costs me a little more work, I prefer the explicit type annotations when they matter (namely, exposed interfaces).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...