Kotlin Context Receivers - How to Use, Why, and Best Practice

Опубликовано: 10 Февраль 2025
на канале: Rock the JVM
5,292
236

blog post: https://blog.rockthejvm.com/kotlin-co...
Complete Kotlin course: https://rockthejvm.com/p/kotlin-essen...

This video is a long-form tutorial on how to use context receivers, a relatively new feature of the Kotlin language.

We talk about
why context receivers are useful when we need increased (but locally available) abstractions
how to allow some functionality for some types and not others
how to control which scopes grant which functionality
how to disallow compiler-legal but nonsensical calls
how to not abuse context receivers and do dependency injection right
some comparisons with Scala, type classes and a version of a pattern called tagless final

We'll look at the need to add extension methods, then the need to abstract extension methods only for some types and not for others. We will introduce the concept of "receiver" and "dispatch receiver" to understand how we can technically solve the problem of selective abstraction.

To overcome the inherent limtations, we'll use context receivers to
allow some functions for some types and not others
control which scopes grant which functions
disallow compiler-legal but non-sensical calls
implement "implicit" dependency injection

Follow Rock the JVM on:
LinkedIn:   / rockthejvm  
Twitter:   / rockthejvm  
Blog: Blog: https://blog.rockthejvm.com

-------------------------------------------------------------------------
Home: https://rockthejvm.com
-------------------------------------------------------------------------