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: _overviews/scala3-book/taste-toplevel-definitions.md
+8-3Lines changed: 8 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -12,6 +12,8 @@ next-page: taste-summary
12
12
In Scala 3, all kinds of definitions can be written at the “top level” of your source code files.
13
13
For instance, you can create a file named _MyCoolApp.scala_ and put these contents into it:
14
14
15
+
{% tabs toplevel_1 class=tabs-scala-version %}
16
+
{% tab 'Scala 3 only' for=toplevel_1 %}
15
17
```scala
16
18
importscala.collection.mutable.ArrayBuffer
17
19
@@ -37,15 +39,18 @@ type Money = BigDecimal
37
39
p.toppings +=Cheese
38
40
println("show me the code".capitalizeAllWords)
39
41
```
42
+
{% endtab %}
43
+
{% endtabs %}
40
44
41
45
As shown, there’s no need to put those definitions inside a `package`, `class`, or other construct.
42
46
43
-
44
47
## Replaces package objects
45
48
46
49
If you’re familiar with Scala 2, this approach replaces _package objects_.
47
50
But while being much easier to use, they work similarly: When you place a definition in a package named _foo_, you can then access that definition under all other packages under _foo_, such as within the _foo.bar_ package in this example:
48
51
52
+
{% tabs toplevel_2 class=tabs-scala-version %}
53
+
{% tab 'Scala 3 only' for=toplevel_2 %}
49
54
```scala
50
55
packagefoo {
51
56
defdouble(i: Int) = i *2
@@ -58,9 +63,9 @@ package foo {
58
63
}
59
64
}
60
65
```
66
+
{% endtab %}
67
+
{% endtabs %}
61
68
62
69
Curly braces are used in this example to put an emphasis on the package nesting.
63
70
64
71
The benefit of this approach is that you can place definitions under a package named _com.acme.myapp_, and then those definitions can be referenced within _com.acme.myapp.model_, _com.acme.myapp.controller_, etc.
0 commit comments