Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

scala: Any default apply method in a class?

Does scala provide a default apply method for a class?

I have a class:

class Player(tea: String, sal: Int = 0) {
    val team  = tea
    private val salary = sal
}

So no apply method here, and I haven’t defined any companion object for it, so no apply method from there too.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I am able to do:

val player = Player("AAAA", 1000)

With no ‘new’ operator used, I understand that this line of code must invoke some apply method. But there is none defined by me. So how does it work?

>Solution :

Yes, since Scala 3, as described in the docs:

Scala case classes generate apply methods, so that values of case classes can be created using simple function application, without needing to write new.

Scala 3 generalizes this scheme to all concrete classes. Example:

class StringBuilder(s: String):
  def this() = this("")

StringBuilder("abc")  // old: new StringBuilder("abc")
StringBuilder()       // old: new StringBuilder()

This works since a companion object with two apply methods is generated together with the class. The object looks like this:

object StringBuilder:
  inline def apply(s: String): StringBuilder = new StringBuilder(s)
  inline def apply(): StringBuilder = new StringBuilder()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading