Skip to content

Update singleton-objects.md #3131

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 2 commits into from
Dec 20, 2024
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
8 changes: 8 additions & 0 deletions _tour/singleton-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,14 @@ scalaCenterEmail match

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.

A note about `Option`, `Some`, and `None` in the code above:
* `Option` is a data type which allows for optionality. It has two cases: `Some` and `None`
* `Some` above represents a match: the emailString, when split by a @, returns an array with two components. This allows creation of a valid instance of class Email.
* `None` above represents no match: the emailString, when split by a @, did not return an array with two components. It could not allow creation of a valid instance of class Email.
* The `Option` return type can then be used in a match/case:
* For a `Some` result, the match knows the returned value is an instance of `Email`, so it can access the inner `username` and `domainName`.
* For a `None` result, the match knows the returned value is not an instance of `Email`, so it prints an appropriate error message.

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.

## Notes for Java programmers ##
Expand Down