FP Module 2 - 101 Scala
Bubu
7,240 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Companion: the best friend of a Class
A companion object is an object with the same name as a class or trait and defined in the same source file as the associated file or trait.
A companion object differs from other objects as it has access rights to the class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.
// Pizza class
class Pizza (var crustType: String) {
override def toString = "Crust type is " + crustType
}
// companion object
object Pizza {
val CRUST_TYPE_THIN = "thin"
val CRUST_TYPE_THICK = "thick"
def getFoo = "Foo"
}
println(Pizza.CRUST_TYPE_THIN) // print "thin"
println(Pizza.getFoo) // print "Foo"
val p = new Pizza(Pizza.CRUST_TYPE_THICK)
println(p) // print "Crust type is thick"
User("John", "Doe") should return an instance of User named John Doe
Suggested playgrounds
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package fp101.tp01.classes
object ExerciceCompanion {
/**
* For this exercise, the User class has its constructor and fields private
* new User("x", "y") does not work anymore
*/
class User private (private val firstName: String, private val lastName: String)
/**
*
* Complete the companion object of the User class such as the code bellow:
* val u = User("John", "Snow") // create an user John Snow and assigned it to u
*
*/
object User{
/**
*
* The apply method is executed when using the User as a function
*
* define the apply function bellow such as:
* User("John", "Snow") // returns an instance of the User class
*
* hint: As a companion object, User object can access to privates fields and methods, including constructor
*/
def apply(firstName: String, lastName: String): User = ???
Enter to Rename, Shift+Enter to Preview