gerbowl.blogg.se

Mapof kotlin
Mapof kotlin





mapof kotlin

After a day of receiving shipments and selling ice cream, we need to update our store’s inventory map. The forEach method performs an action on each entry in a given map. This means that implementing common things like grouping or counting should, in most cases, not be implemented from scratch but rather be done with existing functionalities from the standard library.As a final example, we’ll use what we’ve learned already and introduce the forEach method. Since Kotlin comes with a very useful standard library, you want to consider using it as much as possible. As documented, the getValue function has to be used. Similar to Python, you can initialize a map with a default value provider but need to be aware that the regular index operation access won't work the way you might expect. There are dozens of ways to solve the given problem in Kotlin, but probably the simplest one is a functional approach: fun countOccurrences(values: Collection): Map =Īs shown in this little article, you can solve simple algorithms in many different ways using Kotlin. It still uses an explicit for loop but got simplified by the use of apply which allows us to initialize the map in a single statement. Let me provide you with a simplified version of our code: fun countOccurrences(values: Collection): Map = Nevertheless, it's good to know the alternatives because, in certain situations, you might opt to go with an iterative approach. Most cases can be solved much simpler using Kotlin's outstanding functional APIs which come with built-in grouping and counting functionalities. But, is it idiomatic to write code as we did in the examples above anyway? I think it depends. Let's go idiomaticĪll right, so saw that Kotlin indeed comes with means of default values in maps, which is fantastic. Since default maps want to fulfill this contract, they cannot return anything but null in the case of non-existent keys, which has been discussed in the Kotlin forum before. Returns the value corresponding to the given, or null if such a key is not present in the map. The reason for this is the contract of the Map interface, which says: Instead, it provides a default value for unknown keys, which can be really helpful for grouping and counting algorithms like the following one: from collections import defaultdictĭata = The defaultdict can also be used with other types and makes sure that you don't get a KeyError when running your code. You can find the Python defaultdict documentation and some examples here but the basic use case is shown in the following snippet: from collections import defaultdict Kotlin also comes with a similar tool which I want to demonstrate in this little article. Have you ever used a default map or default dict before? If you know Python a bit, you probably saw its defaultdict in action at some point. By s1m0nw1 1 Comment Does Kotlin have a default Map?







Mapof kotlin