Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
Read the whole series:
Part 1 — type inference
Part 2 — traits
Part 3 — case class/object (ADTs)
Part 4 — apply & unapply functions
Part 5 — implicits <- you’re here
Having looked at case class and extractors recently, the next logical thing would be partial functions. Since Andrea pointed me to a really well article on the subject I don’t think there’s anything else for me to add, so instead, let’s look at Scala’s implicits, which is a very powerful language feature that enables some interesting patterns in Scala.
implicit operator in .Net
You can define both implicit and explicit operators in C#, which allows you to either:
- implicitly converts a type to another in assignment, method argument, etc.; or
- explicitly cast a type to another
F# on the other hand, is a more strongly typed language and does not allow such implicit type conversion. You can still implement and use existing implicit operators created in C#, which is available to you as a static member op_Implicit on the type it’s defined on.
For example.
Additionally, you can also create type extensions to add extension methods AND properties to a type. Whilst this is the idiomatic F# way, these extension members are only visible to F# (and not to C#).
implicit in Scala
Where the implicit operator in .Net (or more specifically, in C#) is concerned with type conversion, implicit in Scala is far more generalised and powerful.
Scala’s implicit comes in 3 flavours:
- implicit parameters
- implicit conversions
- implicit classes
implicit parameters
You can mark the last parameter of a function as implicit, which tells the compiler that the caller can omit the argument and the compiler should find a suitable substitute from the closure.
For example, take the multiplyImplicitly function below.
The last argument is omitted at invocation but the compiler sees a suitable substitute – mult – in scope because:
- it’s the right type – Multiplier
- it’s declared as implicit
and implicitly applies it as the second argument to complete the invocation.
That’s right, only val/var/def that are declared as implicit can be used as an implicit argument.
If mult was not declared as implicit, then a compiler error awaits you instead.
What if there are more than one matching implicit value in scope?
Then you also get a compiler error.
Unsurprisingly, implicit var also works, and given the mutable nature of var it means multiplyImplicitly can yield different value depending on when it’s called.
Finally, you can also use an implicit def (which you can think of as a property, it is evaluated each time but it doesn’t have to be attached to an object).
A common use case for implicit parameters is to implicitly use the global ExecutionContext when working with Scala’s Future. Similarly, the Akka framework use implicit to pass around ActorContext and ActorSystem objects.
implicit conversions
What if you define a higher-order function that takes in another function, f, as argument, can f be chosen implicitly as well?
Yes, it can. It is in fact a common pattern to achieve implicit type conversion (similar to .Net’s implicit operator as we saw at the start of this post).
Notice in the above that show(“42”) compiles even though we haven’t defined an implicit function of the signature String => String. We have the built-in identity function to thank for that.
Just before the Scala compiler throws a typemismatch exception it’ll look for suitable implicit conversion in scope and apply it. Which means, our implicit conversions can be useful outside of the show function too.
And you’re protected by the same guarantee that there can only be one matching implicit function in scope.
What if there’s a more generic implicit conversion with the signature Any -> String, would the compiler complain about ambiguous implicit values or is it smart enough to use intToStr for Int?
It’s smart enough and does the right thing.
implicit classes
Finally, we have implicit classes which allows you to implement .Net style extension methods.
You must create the implicit class inside another object/trait/class, and it
and the class can take only one non-implicit argument in the constructor.
Note that in addition to extension methods, you can also create extension values and properties with implicit class. Which, as we mentioned at the start of the post, is something that you can also do with F#’s type extensions mechanism.
Links
- Scala partial functions (without a PhD)
- SO : understanding implicit in Scala
- Scala School : view bounds
- Implicit design patterns in Scala
- Scala Cats documentation on Type Classes
- Scala: the global ExecutionContext makes your life easier
- Implicit parameters in Scala
- Implicit functions in Scala
- Implicit classes in Scala
- SO : ‘def’ vs ‘val’ vs ‘lazy val’ evaluation in Scala
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.