Skip to content

Commit 92a5370

Browse files
authored
Merge pull request #2956 from ckipp01/mainMethodUpdates
docs: show example usage of `CommandLineParser.FromString`
2 parents e372974 + fbdb689 commit 92a5370

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

_overviews/scala3-book/methods-main-methods.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,33 @@ $ scala happyBirthday sixty Fred
8686
Illegal command line: java.lang.NumberFormatException: For input string: "sixty"
8787
```
8888

89+
## User-defined types as parameters
90+
91+
As mentioned up above, the compiler looks for a given instance of the
92+
`scala.util.CommandLineParser.FromString` typeclass for the type of the
93+
argument. For example, let's say you have a custom `Color` type that you want to
94+
use as a parameter. You would do this like you see below:
95+
96+
{% tabs method_3 %}
97+
{% tab 'Scala 3 Only' for=method_3 %}
98+
99+
```scala
100+
enum Color:
101+
case Red, Green, Blue
102+
103+
given ComamndLineParser.FromString[Color] with
104+
def fromString(value: String): Color = Color.valueOf(value)
105+
106+
@main def run(color: Color): Unit =
107+
println(s"The color is ${color.toString}")
108+
```
109+
110+
{% endtab %}
111+
{% endtabs %}
112+
113+
This works the same for your own user types in your program as well as types you
114+
might be using from another library.
115+
89116
## The details
90117

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

0 commit comments

Comments
 (0)