elreqop.blogg.se

Kotlin map for each
Kotlin map for each










kotlin map for each

Okay, so we imagine there’s a project out there that requires maps to be printed in a custom way which the team implements with the help of a simple extension function. Let’s look at an example and make sure we understand the concepts presented here since we’re going to build on top of these fundamentals in the remainder of this article 😊. Instead, the compiler generates a static function that takes the extension’s receiver as its argument. When we write an extension function for example to add functionality to the much-loved Map class, this does not change the original Map source code in any way. This isn’t some kind of magic but boils down to being syntactic sugar provided by Kotlin. Basically, an extension function allows adding functionality to existing classes without having to modify those classes directly. To start things off, we want to recap what extension functions are and how we can use them in Kotlin. Let’s dive right in! Extension Functions and what are “Receivers” anyway? understanding extension functions, and move on to the more advanced stuff after that. We are going to start with the basics, i.e. Don’t worry if the above does not seem to make sense to you yet.

kotlin map for each

You can read the initial proposal and discussion in this YouTrack issue from 2015 (by Damian Wieczorek). Some time ago, even before Kotlin was released in version 1.0, individuals noticed that extension functions are great but could become even more powerful by allowing not only a single but multiple receivers. Making this a member function of a different class adds even more context to that function as it can only be called from the context of the enclosing class. With an extension function, you specify a receiver object that this function can be called on. We already know extension functions that are highly relevant in this article's setting. Adding context to Kotlin functions was possible even before context receivers entered the game. The language makers decided to come up with a prototype to demonstrate the design proposal solving the highly popular use case of adding context to Kotlin functions. Over a year ago, in February 2022, when Kotlin 1.6.20 was released, the language introduced context receivers for the first time. Why Kotlin needs Context Receivers and how to use them












Kotlin map for each