Converting Between Lists and Maps

Your next task in NyetHack is to charge your patrons the correct amount for their orders. To accomplish this, you can make another map that has names of menu items as keys and their prices as values. Previously, you solved the issue of parsing menu item names by introducing a new list called menuItems using the List constructor. Map does not have an equivalent constructor, but there are other ways to get your hands on a map.

Much like how you can convert a list to a set and vice versa, it is also possible to convert lists to maps with the toMap function – but with a slight catch. toMap is only available on lists that hold Pairs. So it is valid to call toMap on List<Pair<String, Double>>, but not on ...

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.