Scala implicit conversion

Be careful ! I am going to show you something that you have to be really careful about.

With great power comes great responsibilities.

The construct implicit def allows you to implicitly convert from one type to another.

The syntax is pretty straightforward:

implicit def [NAME](input: INPUT_TYPE): OUTPUT_TYPE = ???

It is usually named either from[INPUT_TYPE]To[OUTPUT_TYPE] or in our case since it is already contained inside of the companion object, simply to[OUTPUT_TYPE].

You have to be careful however. You can trap yourself.

For instance, if by mistake you are passing the name of the user in the id field, in a normal situation, the compiler would break and tell you that you are giving a String when the method expect an Int and that will catch your mistake.

However, let's say you want to make your life easier for a different use case, you implement an implicit conversion that automatically convert String to Int. At this point, the compiler will automatically convert any String to Int which can create a real mess.

I would suggest to use implicit def extremely carefully and in very limited scope. Also, do not implement implicit conversion for basic types such as String or Int, but only for more complex types like trait or case class. So that you have a more refined control on when it is used.

Reveal more information and clues
Load Exercise