Skip to content

add code tabs in num15. #2588

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 7, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions _overviews/scala3-book/taste-toplevel-definitions.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ next-page: taste-summary
In Scala 3, all kinds of definitions can be written at the “top level” of your source code files.
For instance, you can create a file named _MyCoolApp.scala_ and put these contents into it:

{% tabs toplevel_1 %}
{% tab 'Scala 3 only' for=toplevel_1 %}
```scala
import scala.collection.mutable.ArrayBuffer

Expand All @@ -37,15 +39,18 @@ type Money = BigDecimal
p.toppings += Cheese
println("show me the code".capitalizeAllWords)
```
{% endtab %}
{% endtabs %}

As shown, there’s no need to put those definitions inside a `package`, `class`, or other construct.


## Replaces package objects

If you’re familiar with Scala 2, this approach replaces _package objects_.
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:

{% tabs toplevel_2 %}
{% tab 'Scala 3 only' for=toplevel_2 %}
```scala
package foo {
def double(i: Int) = i * 2
Expand All @@ -58,9 +63,9 @@ package foo {
}
}
```
{% endtab %}
{% endtabs %}

Curly braces are used in this example to put an emphasis on the package nesting.

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.