Closed
Description
In section "Defining a case class" :
Scala 2 and 3
case class Book(isbn: String)
val frankenstein = Book("978-0486282114")
Notice how the keyword new was not used to instantiate the Book case class.
This is because case classes have an apply method by default which takes care of object construction.
Keyword new does not have to be used explicitly.
It can be though, hence the ambiguity.
As stated in "Classes" part of the Tour of Scala, section "Defining a class" :
Scala 3
class User
val user1 = User()
We call the class like a function, as User(), to create an instance of the class.
It is also possible to explicitly use the new keyword, as new User(), although that is usually left out.
For context:
- Starting Scala
- In Java, keyword new is always mandatory when usable (at least until version 8 included).
- In Dart, keyword new is never mandatory (from version 2).
- Just ran my first Scala program to test this.
- Think this ambiguity comes from Scala 2 where keyword new is mandatory for "Classes" but not for "Case Classes".
Can make a PR if asked. Here is a try :
Although that is usually left out, it is possible to explicitly use the **new** keyword, as **new Book()**.
This is because case classes have an apply method by default which takes care of object construction.
Metadata
Metadata
Assignees
Labels
No labels