Java classes contain two completely different types of members - instance members (e.g., BigDecimal.plus ) and static members (e.g., BigDecimal.valueOf ). Scala has members only . This is actually a simplification! But that leaves a problem: where do we put methods like valueOf ? Where objects are useful.
class BigDecimal(value: String) { def plus(that: BigDecimal): BigDecimal = // ... } object BigDecimal { def valueOf(i: Int): BigDecimal = // ... }
You can view this as a declaration of an anonymous class and one copy of it:
class BigDecimal$object { def valueOf(i: Int): BigDecimal =
When reading Scala code, it is important to distinguish between types and values. I configured IntelliJ to hightlight blue types.
val ls = List.empty[Int]
Java also has another degree of complexity that has been removed in Scala - the distinction between fields and methods. Fields are not allowed on interfaces, unless they are static and finite; methods can be overridden, fields are hidden instead if they are overridden in a subclass. Scala eliminates this complexity and only provides methods to the programmer.
Finally, glib's answer to your second question: if you do not declare any objects, you can never run the program, since you must define the equivalent of public static void main(String... args) {} in Scala, you need though would be one object!
retronym
source share