In this article we combine opaque
type alias hierarchies with implicit resolutions to do calculations.
Scala 3 brings several language enhancements that give programmers even better control over types . One of them is opaque
keyword.
For a deeper look what opaque is please visit opaques page at dotty.epfl.ch.
Let’s continue with an example and define some types:
|
|
Let’s explain these things a bit.
We have declared several new type aliases in types
scope (in our case scope is package types
). Inside of the types
scope all of these aliases works as ordinary type aliases, so we can easily create “constructor” functions. Also we declared “base aliases” named StringBased
and IntBased
. So expression: TString1 <: StringBased
we understand that TString1
is subtype of StringBased
.
Let’s imagine we need do a calculation with our new types, let us call it Transformer
.
|
|
In package transformers
we defined also basic transformers stringTransformer
, and intTransformer
. These functions return input parameter prefixed by some text.
given
is new keyword introduced in Scala 3, it is substitution for constructs like implicit val
or implicit def
.
Let’s put everything together into a running example:
|
|
Run example here. result should be
string transformer: Hello
TString2 transformer: Hello2
int transformer: 42
We can easily use type hierarchies for specialization, see : given String2Transformer:Transformer[TString2] ...
.
And of course, one can do more abstraction with union or intersection types used together with opaque type
construct.