You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
info("Created projects") // Prints "INFO: Created projects"
44
73
}
45
74
```
75
+
{% endtab %}
76
+
77
+
{% tab 'Scala 3' for=singleton-usage-example %}
78
+
79
+
```scala
80
+
importlogging.Logger.info
81
+
82
+
classProject(name: String, daysToComplete: Int)
83
+
84
+
classTest:
85
+
valproject1=Project("TPS Reports", 1)
86
+
valproject2=Project("Website redesign", 5)
87
+
info("Created projects") // Prints "INFO: Created projects"
88
+
```
89
+
{% endtab %}
90
+
91
+
{% endtabs %}
92
+
46
93
47
94
The `info` method is visible because of the import statement, `import logging.Logger.info`.
48
95
@@ -53,8 +100,11 @@ Note: If an `object` is not top-level but is nested in another class or object,
53
100
## Companion objects
54
101
55
102
An object with the same name as a class is called a _companion object_. Conversely, the class is the object's companion class. A companion class or object can access the private members of its companion. Use a companion object for methods and values which are not specific to instances of the companion class.
The `class Circle` has a member `area` which is specific to each instance, and the singleton `object Circle` has a method `calculateArea` which is available to every instance.
74
145
75
146
The companion object can also contain factory methods:
caseNone=> println("Error: could not parse email")
192
+
```
193
+
{% endtab %}
194
+
195
+
{% endtabs %}
196
+
98
197
The `object Email` contains a factory `fromString` which creates an `Email` instance from a String. We return it as an `Option[Email]` in case of parsing errors.
99
198
100
199
Note: If a class or object has a companion, both must be defined in the same file. To define companions in the REPL, either define them on the same line or enter `:paste` mode.
0 commit comments