Fun with Type Hints

Basic usage of :

: can be used to give the compiler a hint what type is expected and be used to trigger implicit transformations.

In the given example 42 is of type Int . With :  Double a Double is requested. So the compiler tries to find a way to have 42 transformed to Double.

We are lucky that implicit is in Scope and the transformation succeeds

If there is no implicit in scope the transformation fails:

Using chained calls to :

With parentheses the usage of : can be chained:

So what can this be used for ?

DSL like use of : to transform Data

Imagine we want to transform Strings and make the of transformations we have applied visible to the Type System.

Cases

String with no Whitespaces

"Hello World" => "HelloWorld"

String in L33tSp34ak

"Hello World" => "H3ll0 W0rld"

Usage Examples

Basic Usage

The Basic usage is quite simple.
Starting out with a NonTransformedString one transformation is applied:

Usage of chained calls

These transformation can also be chained to apply the transformations in the order of the given type transformations.
This is similar to the effect one tries to achieve with the pipe pattern.

Variants to express the same commands

Using :

Using implicitly[T]

Using implicitly to trigger the implicit resolution gets quite verbose:

Calling the methods directly

One could argue that calling the methods directly is far easier and less glue code is needed. As long as the ordering is not important that is true.
But given that the transformations have to be read from the „inside“ to the „outside“ this could lead to subtile errors easily.

Code

Here an example implementation:

Base trait StringTransformer

The Basic Trait String Transformer and a helper Trait StringTransformerCompanion to keep the Code clean.
The implicit String transformation is an additional helper to make the transformation back to String easier.

Basic case class, start class NonTransformedString

Transformers

Here the two example transformers are defined using the Basic Traits. For each class there is a implicit from the generic StringTransformer to a specific StringTransformer. This allows chaining.

Schreib einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *