This means namesAndScores is a map with strings as keys and integers as values, that is, a map from strings to integers. In this example, the type of the map is inferred to be MutableMap. The mapOf() function returns an immutable map of fixed size.įor your card game from an earlier chapter, instead of using the two arrays to map players to their scores, you can use a map: var namesAndScores = mutableMapOf( The concrete type that is created depends on which standard library function is called. Note that Map is an interface, which you’ll learn more about later on. The Kotlin Pair objects are created using the infix to function. This function takes a list of Kotlin Pair objects separated by commas: var yearOfBirth = mapOf( The easiest way to create a map is by using the standard library mapOf() function. In a map, the keys can be of any type and are generally in no particular order. How is this different from an array? With an array, you can only fetch a value by its index, which has to be an integer, and all indexes have to be sequential. For example, the table of contents of this book maps chapter names to their page numbers, making it easy to skip to the chapter you want to read. Maps are useful when you want to look up values by means of an identifier. All keys have to be of the same type, and all values have to be of the same type. The same key can’t appear twice in a map, but different keys may point to the same value. ![]()
0 Comments
Leave a Reply. |