Skip to content

Commit 6333271

Browse files
committed
new classes tour
1 parent 0874633 commit 6333271

File tree

1 file changed

+76
-17
lines changed

1 file changed

+76
-17
lines changed

tutorials/tour/_posts/2017-02-13-classes.md

Lines changed: 76 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,46 +9,105 @@ categories: tour
99
num: 4
1010
next-page: traits
1111
previous-page: unified-types
12+
topics: classes
13+
assumed-knowledge: no-return-keyword, type-declaration-syntax, string-interpolation
1214
---
1315

14-
Classes in Scala are static templates that can be instantiated into many objects at runtime.
15-
Here is a class definition which defines a class `Point`:
16+
Classes in Scala are blueprints for creating objects. They can contain methods,
17+
values, and variables, which are collectively called _members_.
18+
19+
## Defining a class
20+
A minimal class definition is simply the keyword `class` and
21+
an identifier:
22+
```tut
23+
class MyClass
24+
```
25+
However, a class will often have a primary constructor and a body as well. Here is an example class definition for a point:
1626

1727
```tut
1828
class Point(var x: Int, var y: Int) {
29+
1930
def move(dx: Int, dy: Int): Unit = {
2031
x = x + dx
2132
y = y + dy
2233
}
34+
2335
override def toString: String =
24-
"(" + x + ", " + y + ")"
36+
s"($x, $y)"
2537
}
2638
```
2739

28-
Classes in Scala are parameterized with constructor arguments. The code above defines two constructor arguments, `x` and `y`; they are both visible in the whole body of the class.
40+
This `Point` class has four members: the variables `x` and `y` and the methods `move` and
41+
`toString`. Unlike many other languages, the primary constructor is in the class signature `(var x: Int, var y: Int)`. The `move` method takes two integer arguments but does not return a value (the return type `Unit` corresponds to `void` in Java-like languages). `toString`, on the other hand, does not take any parameters but returns a `String` value. Since `toString` overrides the inherited `toString` method, it is tagged with the `override` keyword.
42+
43+
## Constructors
44+
45+
Constructors can have optional parameters by providing a default value like so:
2946

30-
The class also includes two methods, `move` and `toString`. `move` takes two integer arguments but does not return a value (the return type `Unit` corresponds to `void` in Java-like languages). `toString`, on the other hand, does not take any parameters but returns a `String` value. Since `toString` overrides the pre-defined `toString` method, it is tagged with the `override` keyword.
47+
```tut
48+
class Point(var x: Int = 0, var y: Int = 0)
49+
50+
val origin = new Point()
3151
32-
Note that in Scala, it isn't necessary to say `return` in order to return a value. The value returned from a method is simply the last value in the method body. In the case of the `toString` method above, the expression after the equals sign is evaluated and returned to the caller.
52+
println(origin) // (0, 0)
53+
```
3354

34-
Classes are instantiated with the `new` primitive, as follows:
55+
Optional parameters give you a lot of flexibility but if you still need more flexibility, you can create auxiliary constructors which are procedures (i.e. a `def` with no `=` and no return type).
3556

3657
```tut
37-
object Classes {
38-
def main(args: Array[String]) {
39-
val pt = new Point(1, 2)
40-
println(pt)
41-
pt.move(10, 10)
42-
println(pt)
58+
class Point {
59+
def this(x: Int, y: Int) {
60+
this()
61+
if (x > 100 || y > 100) println("Warning: Out of bounds")
4362
}
4463
}
4564
```
65+
There are few requirements for auxiliary constructors:
66+
* They must start with `def this`
67+
* The parameters must _not_ be declared `val` or `var`
68+
* The first statement in the body must call the primary constructor or another auxiliary constructor. In the example above, the implicit primary constructor, `this()`, is called.
69+
70+
## Member scope
71+
Methods are public by default. Use the `private` access modifier
72+
to hide them from outside of the class.
73+
```tut
74+
import scala.math._
75+
76+
class Point(var x: Double, var y: Double) {
77+
private def distanceFromOrigin = sqrt(x * x + y * y)
78+
79+
override def toString: String =
80+
s"Point: ($x, $y), Distance from origin: $distanceFromOrigin"
81+
}
82+
```
83+
84+
You can also simply nest private methods inside of the public ones
85+
that use them:
86+
87+
```tut
88+
import scala.math.sqrt
89+
90+
class Point(var x: Double, var y: Double) {
4691
47-
The program defines an executable application Classes in form of a top-level [singleton object](singleton-objects) with a `main` method. The `main` method creates a new `Point` and stores it in value `pt`. Note that values defined with the `val` construct are different from variables defined with the `var` construct (see class `Point` above) in that they do not allow updates; i.e. the value is constant.
92+
override def toString: String = {
93+
def distanceFromOrigin = sqrt(x * x + y * y)
4894
49-
Here is the output of the program:
95+
s"Point: ($x, $y), Distance from origin: $distanceFromOrigin"
96+
97+
}
98+
}
99+
```
100+
101+
Primary constructor parameters with `val` and `var` are public. However, because `val`s are immutable, you can't write the following.
102+
```
103+
class Point(val x: Int, val y: Int)
104+
val point = new Point(1, 2)
105+
val.x = 3 // <-- does not compile
106+
```
50107

108+
Parameters without `val` or `var` are private values, visible only within the class and its subclasses.
51109
```
52-
(1, 2)
53-
(11, 12)
110+
class Point(x: Int, y: Int)
111+
val point = new Point(1, 2)
112+
val.x // <-- does not compile
54113
```

0 commit comments

Comments
 (0)