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 Video Library
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
View Events Video Library
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
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

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

A Guide to Continuous Integration and Deployment: Learn the fundamentals and understand the use of CI/CD in your apps.

Related

  • Transitioning From Groovy to Kotlin for Gradle Android Projects
  • Building Pop-Up Compose Notifications in Android Using Kotlin and Compose
  • New ORM Framework for Kotlin
  • Pessimistic and Optimistic Locking With MySQL, jOOQ, and Kotlin

Trending

  • Optimizing Generative AI With Retrieval-Augmented Generation: Architecture, Algorithms, and Applications Overview
  • Converting ActiveMQ to Jakarta (Part 1)
  • JBang: How to Script With Java for Data Import From an API
  • The Resurrection of Virtual Threads: Unraveling Their Journey From JDK 1.1 to JDK 21
  1. DZone
  2. Coding
  3. Languages
  4. Kotlin: Reified Type Parameters

Kotlin: Reified Type Parameters

Want to see how Kotlin reifies generic type parameters and what doors that opens up for you? Let's walk through some sample code that uses Jackson.

Biju Kunjummen user avatar by
Biju Kunjummen
·
Jan. 26, 18 · Tutorial
Like (2)
Save
Tweet
Share
16.0K Views

Join the DZone community and get the full member experience.

Join For Free

This post walks through a sample that demonstrates Kotlin's ability to cleverly reify generic type parameters.

So consider first a world where Kotlin does not support this feature. If we were using the Jackson library to convert JSON to a Map with String-based keys and Integer-based values, I would use code along these lines:

@Test
fun `sample parameterized retrieval raw object mapper`() {
    val objectMapper = ObjectMapper()
    val map: Map<String, Int> = objectMapper.readValue("""
        | {
        |   "key1": 1,
        |   "key2": 2,
        |   "key3": 3
        | }
        """.trimMargin(), object : TypeReference<Map<String, Int>>() {})

    assertThat(map).isEqualTo(mapOf("key1" to 1, "key2" to 2, "key3" to 3))
}


TypeReference, used above, implements a pattern called a Super type token, which allows the type of a parameterized type to be captured by sub-classing. Note the ugly way we create an anonymous sub-class in Kotlin.

object : TypeReference<Map<String, Int>>() {}


What I would like to do is invoke the ObjectMapper the following way instead:

@Test
fun `sample parameterized retrieval`() {
    val om = ObjectMapper()
    val map: Map<String, Int> = om.readValue("""
        | {
        |   "key1": 1,
        |   "key2": 2,
        |   "key3": 3
        | }
        """.trimMargin())

    assertThat(map).isEqualTo(mapOf("key1" to 1, "key2" to 2, "key3" to 3))
}


The generic type parameter is being inferred based on the type of what is to be returned (the left-hand side).

This can be achieved using an extension function on ObjectMapper, which looks like this:

inline fun <reified T> ObjectMapper.readValue(s: String): T = 
        this.readValue(s, object : TypeReference<T>() {})


The inline function is the heart of the support to be able to reify generic type parameters here — after compilation, the function would be expanded out into any place this function is called, and thus, the second version is exactly same as the first version of the test — but reads far better than before.

Note that Jackson already implements these Kotlin extension functions in the excellent jackson-module-kotlin library.

Kotlin (programming language)

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Transitioning From Groovy to Kotlin for Gradle Android Projects
  • Building Pop-Up Compose Notifications in Android Using Kotlin and Compose
  • New ORM Framework for Kotlin
  • Pessimistic and Optimistic Locking With MySQL, jOOQ, and Kotlin

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
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: