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
Copy file name to clipboardExpand all lines: _tour/packages-and-imports.md
+66-3Lines changed: 66 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -14,11 +14,16 @@ Scala uses packages to create namespaces which allow you to modularize programs.
14
14
## Creating a package
15
15
Packages are created by declaring one or more package names at the top of a Scala file.
16
16
17
+
{% tabs packages-and-imports_1 %}
18
+
{% tab 'Scala 2 and 3' for=packages-and-imports_1 %}
17
19
```
18
20
package users
19
21
20
22
class User
21
23
```
24
+
{% endtab %}
25
+
{% endtabs %}
26
+
22
27
One convention is to name the package the same as the directory containing the Scala file. However, Scala is agnostic to file layout. The directory structure of an sbt project for `package users` might look like this:
23
28
```
24
29
- ExampleProject
@@ -34,7 +39,10 @@ One convention is to name the package the same as the directory containing the S
34
39
- test
35
40
```
36
41
Notice how the `users` directory is within the `scala` directory and how there are multiple Scala files within the package. Each Scala file in the package could have the same package declaration. The other way to declare packages is by using braces:
As you can see, this allows for package nesting and provides greater control for scope and encapsulation.
48
68
49
69
The package name should be all lower case and if the code is being developed within an organization which has a website, it should be the following format convention: `<top-level-domain>.<domain-name>.<project-name>`. For example, if Google had a project called `SelfDrivingCar`, the package name would look like this:
50
-
```
70
+
71
+
{% tabs packages-and-imports_3 %}
72
+
{% tab 'Scala 2 and 3' for=packages-and-imports_3 %}
73
+
```scala
51
74
packagecom.google.selfdrivingcar.camera
52
75
53
76
classLens
54
77
```
78
+
{% endtab %}
79
+
{% endtabs %}
80
+
55
81
This could correspond to the following directory structure: `SelfDrivingCar/src/main/scala/com/google/selfdrivingcar/camera/Lens.scala`.
56
82
57
83
## Imports
58
84
`import` clauses are for accessing members (classes, traits, functions, etc.) in other packages. An `import` clause is not required for accessing members of the same package. Import clauses are selective:
0 commit comments