- Contextual parameters are used to pass argument to the functions calls tree without actually passing the parameter to them. For example,
class Theme(val value: String)
val theme = Theme("Dark")
def renderDialog(content: String, theme: Theme): String =
renderBox(s"This is $content", theme)
def renderBox(content: String, theme: Theme): String =
val themeValue = theme.value
s"$content $themeValue"
Here, theme
has to be passed to every function calls again and again. Scala provides the notion of context parameter where compiler can find the argument with the correct type on the call site.
class Theme(val value: String)
val theme = Theme("Dark")
def renderDialog(content: String)(using theme: Theme): String =
renderBox(s"This is $content")
def renderBox(content: String)(using theme: Theme): String =
val themeValue = theme.value
s"$content $themeValue"
So,
renderDialog("Hello")(using theme)
Here, we are only passing the theme context parameter
to renderDialog
and renderBox
implicitly gets the theme
parameter.
There is still we have to pass theme
parameter to the first call renderDialog
. We can omit that using Given Instances