DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Learning Kotlin: The Map Delegate

Learning Kotlin: The Map Delegate

Want to learn how to use the map delegate in Kotlin? Check out this post to learn more about using map values in Kotlin.

Robert Maclean user avatar by
Robert Maclean
·
Sep. 04, 18 · Tutorial
Like (6)
Save
Tweet
Share
11.99K Views

Join the DZone community and get the full member experience.

Join For Free

The next delegate is actually built into something we have looked at before, mapand if you use by to refer to one, when you get the value it goes to the map values to look it up.

As a way to illustrate this, we will take some JSON data and parse it with the kotlinx.serialization code. Then, we loop over each item and convert it into a map, which we use to create an instance of User.

import kotlinx.serialization.json.*

class User(userValues:Map<String, Any?>) {
    val name: String by userValues
    val eyeColour: String by userValues
    val age : String by userValues
}

fun main(args:Array<String>) {
    val json = """[{
       "name":"Robert",
       "eyeColour":"Green",
       "age":36
   },{
       "name":"Frank",
       "eyeColour":"Blue"
   }]""";

    (JsonTreeParser(json).read() as JsonArray)
        .map{  
            val person = it as JsonObject
            person.keys.associateBy({it}, {person.getPrimitive(it).content})
        }.map {
            User(it)
        }.forEach { println("${it.name} with ${it.eyeColour} eyes") }

}


This code outputs:

Robert with Green eyes
Frank with Blue eyes


However, if we change line 25 to include the age, we get a better view of what is happening.

}.forEach { println("${it.name} with ${it.eyeColour} eyes and is ${it.age} years old") }


This simple adjustment changes the output to be:

Robert with Green eyes and is 36 years oldException in thread "main"
java.util.NoSuchElementException: Key age is missing in the map.
        at kotlin.collections.MapsKt__MapWithDefaultKt.getOrImplicitDefaultNullable(MapWithDefault.kt:24)
        at sadev.User.getAge(blog.kt)
        at sadev.BlogKt.main(blog.kt:27)


As you can see, the map is not initializing the values ahead of time. Rather, it is merely being used to look up what value in the map when the properties getter is called. 

Happy delegating!

Kotlin (programming language) Data (computing) Property (programming) JSON Convert (command)

Published at DZone with permission of Robert Maclean, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Deep Dive Into AIOps and MLOps
  • 5 Steps for Getting Started in Deep Learning
  • Collaborative Development of New Features With Microservices
  • Keep Your Application Secrets Secret

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: