Skip to content
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

docs: show example usage of CommandLineParser.FromString #2956

Merged
merged 1 commit into from
Feb 15, 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
27 changes: 27 additions & 0 deletions _overviews/scala3-book/methods-main-methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,33 @@ $ scala happyBirthday sixty Fred
Illegal command line: java.lang.NumberFormatException: For input string: "sixty"
```

## User-defined types as parameters

As mentioned up above, the compiler looks for a given instance of the
`scala.util.CommandLineParser.FromString` typeclass for the type of the
argument. For example, let's say you have a custom `Color` type that you want to
use as a parameter. You would do this like you see below:

{% tabs method_3 %}
{% tab 'Scala 3 Only' for=method_3 %}

```scala
enum Color:
case Red, Green, Blue

given ComamndLineParser.FromString[Color] with
def fromString(value: String): Color = Color.valueOf(value)

@main def run(color: Color): Unit =
println(s"The color is ${color.toString}")
```

{% endtab %}
{% endtabs %}

This works the same for your own user types in your program as well as types you
might be using from another library.

## The details

The Scala compiler generates a program from an `@main` method `f` as follows:
Expand Down
Loading