You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!
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.
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
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.
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.
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.
- 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
Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.
Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.
Skill up your serverless game with this hands-on workshop.
My 4-week Production-Ready Serverless online workshop is back!
This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.
We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.
If you enrol now you can also get 15% OFF with the promo code “yanprs15”.
Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.
Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!
Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- All you need to know about caching for serverless applications
- Lambda optimization tip – enable HTTP keep-alive
- You are wrong about serverless and vendor lock-in
- You are thinking about serverless costs all wrong
- Just how expensive is the full AWS SDK?
- Check-list for going live with API Gateway and Lambda
- How to choose the right API Gateway auth method
- CloudFormation protip: use !Sub instead of !Join
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- Guys, we’re doing pagination wrong
- Top 10 Serverless framework best practices
- How to break the “senior engineer” career ceiling
- My advice to junior developers