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 constructimplicit defallows 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 eitherfrom[INPUT_TYPE]To[OUTPUT_TYPE]or in our case since it is already contained inside of thecompanion object, simplyto[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 aStringwhen the method expect anIntand that will catch your mistake.

However, let's say you want to make your life easier for a different use case, you implement animplicit conversionthat automatically convertStringtoInt. At this point, the compiler will automatically convert anyStringtoIntwhich can create a real mess.

I would suggest to useimplicit defextremely carefully and in very limited scope. Also, do not implementimplicit conversionfor basic types such asStringorInt, but only for more complex types liketraitorcase class. So that you have a more refined control on when it is used.

Reveal more information and clues
Load Exercise