score:112
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).
score:0
One thing : imagine the last statement of a method that should return Unit does not return Unit. Using the non-equal syntax is then very convenient, I hope this will not be deprecated as I see several use case for it
score:0
As time as progressed the default style has changed, and this has been mentioned in many of the comments to answers, it is recommended in the official style guide to use the =
syntax for function declarations.
score:0
for method that dont have a return value, a way to express such methods is leaving out the result type and the equals sign, following the method with a block enclosed in curly braces. In this form, the method looks like a procedure, a method that is executed only for its side effects.
score:4
For methods, Scala Style Guide recommends the equals syntax as opposed to procedure syntax
Procedure Syntax
Avoid the procedure syntax, as it tends to be confusing for very little gain in brevity.
// don't do this
def printBar(bar: Baz) {
println(bar)
}
// write this instead
def printBar(bar: Bar): Unit = {
println(bar)
}
score:12
You must use equals sign in call declarations except the definitions returning Unit.
In this latter case, you may forgo the equals sign. This syntax may be deprecated, though, so it's best avoided. Using equals sign and declaring the return type will always work.
score:42
UPDATE: as of Scala-2.10, using equals sign is preferred. Old answer:
Methods which return Unit
should always use the non-equals syntax. This avoids potential mistakes in implementation carrying over into the API. For example, you could have accidentally done something like this:
object HelloWorld {
def main(args: Array[String]) = {
println("Hello!")
123
}
}
Trivial example of course, but you can see how this might be a problem. Because the last expression does not return Unit
, the method itself will have a return type other than Unit
. This is exposed in the public API, and might cause other problems down the road. With the non-equals syntax, it doesn't matter what the last expression is, Scala fixes the return type as Unit
.
It's also two characters cleaner. :-) I also tend to think that the non-equals syntax makes the code just a little easier to read. It is more obvious that the method in question returns Unit
rather than some useful value.
On a related note, there is an analogous syntax for abstract methods:
trait Foo {
def bar(s: String)
}
The method bar
has signature String=>Unit
. Scala does this when you omit the type annotation on an abstract member. Once again, this is cleaner, and (I think) easier to read.
Source: stackoverflow.com
Related Query
- When to use the equals sign in a Scala method declaration?
- When to use scala triple caret (^^^) vs double caret (^^) and the into method (>>)
- How do I alias the scala setter method 'myvar_$eq(myval)' to something more pleasing when in java?
- Use of recursion in Scala when run in the JVM
- What's the relationship of the versions of scala when I use sbt to build a scala project?
- Scala - how to explicitly choose which overloaded method to use when one arg must be null?
- Should I use `()` or not for the method `getClients` when the return value can be changed?
- Understanding the scala substitution model through the use of sumInts method
- How Scala Array apply method returns the value at the index when the implementation is simply throw new error
- When should a Scala method def use an explicitly defined return type?
- Idea 13 and Gradle when trying to use scala-compiler in the Scala facets does not find scala-library
- When searching for implicit conversion, does Scala use the destination type?
- When should I use Scala method & function
- Can I use a type bound on a Scala abstract method and then "tighten up" the definition in a subclass?
- How does the order of instructions works inside Scala classes when you override a method
- when to use lower bound in scala method
- What is the good code style for scala when calling a method of an object
- Why is Scala unable to infer the type of an anonymous function when there is method overloading and only one method takes a function?
- Do two copies of a case class use twice the memory when only one property is changed, or does Scala reuse immutable values on copy to save memory?
- When programming with 'idiomatic' Scala is the use of 'concrete classes' optional/redundant?
- How do I set the Scala compiler to use a plugin when I build using Maven?
- Scala add extension method when the type params have a common type
- How to use the OR operator within a filter predicate when using _._2 in scala
- scala : use of braces for a function when the parameter is a predicate
- How to design the classes in scala when you want to mock a heavy method in testing?
- In the scala function literal, when do I have to use the "case" keyword
- scala will choose which method when both use default parameters and polymorphism?
- When and why does the collect method fail for filtering Scala Collections by subtype?
- How to use the Scala import clause to import from a method parameter
- How to return a desired datatype from a method in Scala particularly when the method has try/catch block in it?
More Query from same tag
- Scala - List from the end (problem with commas)
- How to use operator LIKE between two columns in Scala?
- interrupting REPL ILoop programmatically
- Cannot compile Flink 1.7.2 for Scala 2.12: Maven enforcer finds banned dependencies
- Scala trait naming convention when trait is the same as class
- Test to prevent java.lang.NoClassDefFoundError
- Writing DataFrame to MemSQL Table in Spark
- scala function returning only single value of list but not all why?
- What is the difference between Abstract Data Types and Algebraic Data Types
- Apache Spark Task Serialization
- Wordspec "should" "when" "in"
- Converting List[JsObject] to JsArray with Fold
- Dynamically merge Akka streams
- "Could not find main method from given launch configuration" when using Java+Scala+Slick2D
- Read multiple files in a folder with Scala for a Spark job
- why org.apache.spark.sql.types.DecimalType's max precision value is 38 in SparkSQL?
- Reading very large files (~ 1 TB) in sequential blocks
- Can't do pattern matching over Option[String] having a different runtime type
- Difference between val and def in scala?
- A hard way to get rid of everything generated by sbt
- How do I use countDistinct in Spark/Scala?
- Scala & MongoDB: POJOs and Scala classes
- scalaj Http header not being recognized
- Chinese Garbled in REPL in scala
- SBT dependency Error
- How to accumulate errors in a functional way upon validating database object?
- Type Conformation Error: Iterable[Int] to expected type List[Int]
- Spray microservice assembly deduplicate
- Consuming and API with Scala Dispatch Same method two different JSON
- Spark App using Scala and SBT in Eclipse