简体   繁体   中英

What are the use-cases for auxiliary constructors in Scala?

For example, how is this:

class Cat(name: String, val age: Int) {
  def this() = this("Garfield", 20)
}

val someCat = new Cat
someCat.age
res0: Int = 20

Different from:

class Cat(name: String = "Garfield", val age: Int = 20)
val someCat = new Cat
someCat.age
res0: Int = 20

Note: I have seen answers to other questions(eg here ) that discuss the differences between Java & Scala in the implementation for auxiliary constructors. But I am mostly trying to understand why do we need them in Scala, in the first place.

Auxiliary constructors are good for more than just supplying defaults. For example, here's one that can take arguments of different types:

class MyBigInt(x: Int) {
  def this(s: String) = this(s.toInt)
}

You can also hide the main constructor if it contains implementation details:

class MyBigInt private(private val data: List[Byte]) {
  def this(n: Int) = this(...)
}

This allows you to have data clearly be the backing structure for your class while avoiding cluttering your class with the arguments to one of your auxiliary constructors.

Another use for auxiliary constructors could be migrating Java code to Scala (or refactoring to change a backing type, as in the example above) without breaking dependencies. In general though, it is often better to use a custom apply method in the companion object, as they are more flexible.

A recurring use case I noticed is, as Brian McCutchon already mentioned in his answer " For example, here's one that can take arguments of different types ", parameters of Option type in the primary constructor. For example:

class Person(val firstName:String, val middleName:Option[String], val lastName: String)

To create a new instance you need to do:

val person = new Person("Guido",  Some("van"), "Rossum")

But with an auxiliary constructor, the whole process will be very pleasant.

  class Person(val firstName:String, val middleName:Option[String], val lastName: String){
    def this(firstName:String, middleName:String, lastName: String) = this(firstName, Some(middleName), lastName)
  }
  val person = new Person("Guido",  "van", "Rossum")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM