Skip to content

Commit

Permalink
docs: show example usage of CommandLineParser.FromString
Browse files Browse the repository at this point in the history
This is covered in the video and briefly mentioned in the text above,
but no example is given. This just provides a small example in written
format to match what is covered in the video.
  • Loading branch information
ckipp01 committed Feb 14, 2024
1 parent 9a12ccb commit fbdb689
Showing 1 changed file with 27 additions and 0 deletions.
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

0 comments on commit fbdb689

Please sign in to comment.