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 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 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 aString
when the method expect anInt
and 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 convertString
toInt
. At this point, the compiler will automatically convert anyString
toInt
which can create a real mess.
I would suggest to useimplicit def
extremely carefully and in very limited scope. Also, do not implementimplicit conversionfor basic types such asString
orInt
, but only for more complex types liketrait
orcase class
. So that you have a more refined control on when it is used.