July 2017
Intermediate to advanced
796 pages
18h 55m
English
As mentioned earlier, static does not exist in Scala. You cannot do static imports and neither can you cannot add static methods to classes. In Scala, when you define an object with the same name as the class and in the same source file, then the object is said to be the companion of that class. Functions that you define in this companion object of a class are like static methods of a class in Java:
class HelloCity(CityName: String) { def sayHelloToCity = println("Hello, " + CityName + "!") }
This is how you can define a companion object for the class hello:
object HelloCity { // Factory method def apply(CityName: String) = new Hello(CityName) }
The equivalent class in Java would look like this:
public ...
Read now
Unlock full access