The programmer has the freedom to choose which values to supply and which values to leave it as default. We can then create an instance and access the variables as follows. case class Book ( val id : Int = - 1, val title : String = "No name", val isbn : Long = - 1 ) Same can be done in case classes as well. We saw in the previous tutorial on how default values can be given to classes using the primary constructor. Note that in case classes, the variables are just val by default and not private val as in regular classes and hence there are no need of special getters. val book = Book ( 100, "Stephen hawking's : A brief history of time", 9788370017361L ) println ( book. Variables can be accessed similar to their class counterparts. This is just for removing verbosity, in fact we can include the new keyword and it works in the same manner.Ĭan be compared syntactically to java strings where they can can be created without using the new keyword as well. val x = Book ( 100, "Stephen hawking's : A brief history of time", 9788370017361L ) Creating classes without the new keywordĬase classes can be created without using the new keyword. This discussion is a separate topic, but if you are in doubt on where to place a case class, then put it in a separate file. Of course this can be different based on the requirement, one can group together multiple case classes into one single file with having similar functionality. We would be tempted to put it along wherever we wan’t since it is just one line, but the scala style guide pretty much sumps up on the styling part. Perfectly valid syntax and it takes just one line of code. The code below declares a class called Book with three member variables id, title, isbn case class Book ( id : Int, title : String, isbn : Long ) Structural equality - Automatic equals generation.Creating classes without the new keyword.: This article has been translated to chinese by This is part 6 of the scala tutorial series. Case classes are very similar to classes, but they do lot of boiler plate stuff and have some neat functionality.
0 Comments
Leave a Reply. |