Skip to content

Ambiguity in Tour of Scala : Case Classes #2771

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
QuentinCazelles opened this issue Apr 17, 2023 · 3 comments
Closed

Ambiguity in Tour of Scala : Case Classes #2771

QuentinCazelles opened this issue Apr 17, 2023 · 3 comments

Comments

@QuentinCazelles
Copy link

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.
@bishabosha
Copy link
Member

bishabosha commented Apr 17, 2023

Thank you for opening the issue!

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.

This seems like a sensible change to me, feel free to go ahead with the PR :)

@preveen-stack
Copy link

I guess this issue can be closed as PR is already merged

@julienrf
Copy link
Contributor

Indeed, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants