From fbdb689851e795ccd387d550ff078e4317cc9c4e Mon Sep 17 00:00:00 2001 From: Chris Kipp Date: Wed, 24 Jan 2024 15:22:16 +0100 Subject: [PATCH] docs: show example usage of `CommandLineParser.FromString` 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. --- .../scala3-book/methods-main-methods.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/_overviews/scala3-book/methods-main-methods.md b/_overviews/scala3-book/methods-main-methods.md index cc26716f1..02d40cc22 100644 --- a/_overviews/scala3-book/methods-main-methods.md +++ b/_overviews/scala3-book/methods-main-methods.md @@ -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: