Scala 101 - First Things First

1, Object Instead of static Methods - Factory Method in Scala

class LikeLadies(ladyName: String) {
    def likeHer() = {
        println(s"I guess I really like ${ladyName}!")
    }
}

object LikeLadies {
    //Factory Method
    def apply(ladyName: String) = {
        new LikeLadies(ladyName)
    }
}

Now we can use val likeLadies = LikeLadies("AngelaBaby") to create a new instance of LikeLadies. This is a less verbose way of doing things and that's how we do things in Scala.

Creative Note:

Mediocre engineers just follow the rules, but leaders create new things.

In Java, we put instance methods and static methods all in the same class. But in Scala, we separate them into class and object. Why are we doing that? All in one place is definitely simpler. Yes, simpler, but not clearer. object in Scala is an example of Singleton design pattern. Scala forces you to create only one instance for static methods to save resources (we don't have to create more instance methods for things that only need to be created once, at the start of the program). So by using object in Scala, you don't have to create your own mechanism of enforcing Singleton design pattern yourself! How wonderful!

Convention:

Make the class and the object of the same name in the same file for consistency.

猜你喜欢

转载自blog.csdn.net/qq_25527791/article/details/88290131