aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Data
  • Programming

Data Classes — The Classy Way To Hold Data

  • aster.cloud
  • November 4, 2020
  • 5 minute read

A Puppy has a name, a breed and a whole lot of cuteness. To model a class that holds just data, you should use a data class. The compiler simplifies your work by auto generating toString(), equals() and hashCode() for you and providing destructuring and copy functionality out of the box letting you focus on the data you need to represent. Read on to learn more about other advantages of data classes, their restrictions and to take a look under the hood of how they’re implemented.

Usage overview

To declare a data class, use the data modifier and specify the properties of the class as val or var parameters in the constructor. As with any function or constructor, you can also provide default arguments, you can directly access and modify properties and define functions inside your class.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

But, you get several advantages over regular classes:

  • <strong class="hz kc">toString()</strong>, <strong class="hz kc">equals()</strong> and <strong class="hz kc">hashCode()</strong> are implemented for you, by the Kotlin compiler, avoiding a series of small human errors that can cause bugs: like forgetting to update them every time you add or update your properties, logic mistakes when implementing hashCode, forgetting to implement hashCode when you’re implementing equals and more.
  • destructuring
  • ease of copying by calling the copy() method:
/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */

data class Puppy(
        val name: String,
        val breed: String,
        var cuteness: Int = 11
)

// create new instances
val tofuPuppy = Puppy(name = "Tofu", breed = "Corgi", cuteness = Int.MAX_VALUE)
val tacoPuppy = Puppy(name = "Taco", breed = "Cockapoo")

// access and modify properties
val breed = tofuPuppy.breed
tofuPuppy.cuteness++


// destructuring
val (name, breed, cuteness) = tofuPuppy
println(name) // prints: "Tofu"

// copy: create a puppy with the same breed and cuteness as tofuPuppy but with a different name
val tacoPuppy = tofuPuppy.copy(name = "Taco")

 

Read More  Protect Your Data With These 4 Tips From ‘Star Wars’

Restrictions

Data classes come with a series of restrictions.

 

Constructor parameters

Data classes were created as a data holder. To enforce this role, you have to pass at least one parameter to the primary constructor and the parameters need to be <strong class="hz kc">val</strong> or <strong class="hz kc">var</strong> properties. Trying to add a parameter without val/var leads to a compile error.

As a best practice, consider using vals instead of vars, to promote immutability. Otherwise, subtle issues can appear for example when using data classes as keys for HashMap objects, as the container can get in an invalid state when the var value changes.

Similarly, trying to add a vararg parameter in the primary constructor leads to a compile error as well:

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */

data class Puppy constructor(
    val name: String,
    val breed: String,
    var cuteness: Int = 11,
   // error: Data class primary constructor must have only property (val / var) parameters         
  playful: Boolean,
  // error: Primary constructor vararg parameters are forbidden for data classes
   vararg friends: Puppy 
)

vararg is not allowed due to how equals() works on the JVM for arrays and collections. Andrey Breslav explains:

Collections are compared structurally, while arrays are not, equals() for them simply resorts to referential equality: this === other.

Inheritance

Data classes can inherit from interfaces, abstract classes and classes but cannot inherit from other data classes. Data classes also can’t be marked as open. For example, adding open will result in an error: Modifier ‘open’ is incompatible with ‘data’.

Under the hood

Let’s check what exactly does Kotlin generate to be able to understand how some of these features are possible. To do this, we’ll look at the Java decompiled code: Tools -> Kotlin -> Show Kotlin Bytecode then press the Decompile button.

Read More  Android Dev Summit 2019 | LiveData with Coroutines and Flow

Properties

Like with a regular class, Puppy is a public final class, containing the properties we defined and the getters and setters for them:

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */

public final class Puppy {
   @NotNull
   private final String name;
   @NotNull
   private final String breed;
   private int cuteness;

   @NotNull
   public final String getName() {
      return this.name;
   }

   @NotNull
   public final String getBreed() {
      return this.breed;
   }

   public final int getCuteness() {
      return this.cuteness;
   }

   public final void setCuteness(int var1) {
      this.cuteness = var1;
   }
...
}

 

Constructor(s)

The constructor we defined is generated. Because we use a default argument in the constructor, then we get the 2nd synthetic constructor as well.

To find out more about default arguments and the generated code, check out this blog post.

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */

public Puppy(@NotNull String name, @NotNull String breed, int cuteness) {
      ...
      this.name = name;
      this.breed = breed;
      this.cuteness = cuteness;
   }

   // $FF: synthetic method
   public Puppy(String var1, String var2, int var3, int var4, DefaultConstructorMarker var5) {
      if ((var4 & 4) != 0) {
         var3 = 11;
      }

      this(var1, var2, var3);
   }
...
}

toString(), hashCode(), equals()

Kotlin generates the toString(), hashCode() and equals() methods. When you modify the data class, updating properties, the right method implementations are generated for you, automatically. Like this, you know that hashCode() and equals() will never be out of sync. Here’s how they look for our Puppy class:

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */

...
  @NotNull
   public String toString() {
      return "Puppy(name=" + this.name + ", breed=" + this.breed + ", cuteness=" + this.cuteness + ")";
   }

   public int hashCode() {
      String var10000 = this.name;
      int var1 = (var10000 != null ? var10000.hashCode() : 0) * 31;
      String var10001 = this.breed;
      return (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31 + this.cuteness;
   }

   public boolean equals(@Nullable Object var1) {
      if (this != var1) {
         if (var1 instanceof Puppy) {
            Puppy var2 = (Puppy)var1;
            if (Intrinsics.areEqual(this.name, var2.name) && Intrinsics.areEqual(this.breed, var2.breed) && this.cuteness == var2.cuteness) {
               return true;
            }
         }

         return false;
      } else {
         return true;
      }
   }
...

While toString and hashCode are quite straightforward an look similar to the way you’d implement it, equals uses <a class="cm ix" href="https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/runtime/kotlin/jvm/internal/Intrinsics.java#L166" target="_blank" rel="noopener nofollow noreferrer">Intrinsics.areEqual</a> that performs a structural equality:

public static boolean areEqual(Object first, Object second) {
    return first == null ? second == null : first.equals(second);
}

By using a method call rather than the direct implementation, the Kotlin language developers get more flexibility, as they can change the implementation of areEqual in future language versions, if needed.

Read More  A New Protocol Buffers Generator For Go

Components

To enable destructuring, data classes generate componentN() methods that just return a field. The component number follows the order of the constructor parameters:

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */
...
   @NotNull
   public final String component1() {
      return this.name;
   }

   @NotNull
   public final String component2() {
      return this.breed;
   }

   public final int component3() {
      return this.cuteness;
   }
...

Find out more about destructuring from our Kotlin Vocabulary post.

Copy

Data classes generate a copy() method that can be used to create a new instance of the object, keeping 0 or more of the original values. You can think of copy() as a method that gets all fields of the data class as parameters, with the values of the fields as default values. Knowing this, you won’t be surprised that Kotlin generates 2 copy() methods: copy and copy$default. The latter is a synthetic method that ensures that when a value isn’t passed in for a parameter, then the right value is used from the base class:

/* Copyright 2020 Google LLC.	
   SPDX-License-Identifier: Apache-2.0 */
...
@NotNull
   public final Puppy copy(@NotNull String name, @NotNull String breed, int cuteness) {
      Intrinsics.checkNotNullParameter(name, "name");
      Intrinsics.checkNotNullParameter(breed, "breed");
      return new Puppy(name, breed, cuteness);
   }

   // $FF: synthetic method
   public static Puppy copy$default(Puppy var0, String var1, String var2, int var3, int var4, Object var5) {
      if ((var4 & 1) != 0) {
         var1 = var0.name;
      }

      if ((var4 & 2) != 0) {
         var2 = var0.breed;
      }

      if ((var4 & 4) != 0) {
         var3 = var0.cuteness;
      }

      return var0.copy(var1, var2, var3);
   }
...

Conclusion

Data classes are one of the most used Kotlin features and for a good reason — they decrease the boilerplate code you need to write, enable features like destructuring and copying an object and let you focus on what matters: your app.

This article is republished from Medium by Florina Muntenescu.


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster.cloud

Related Topics
  • Android
  • Data
  • Medium
You May Also Like
Getting things done makes her feel amazing
View Post
  • Computing
  • Data
  • Featured
  • Learning
  • Tech
  • Technology

Nurturing Minds in the Digital Revolution

  • April 25, 2025
View Post
  • Data
  • Engineering

Hiding in Plain Site: Attackers Sneaking Malware into Images on Websites

  • January 16, 2025
IBM and Ferrari Premium Partner
View Post
  • Data
  • Engineering

IBM Selected as Official Fan Engagement and Data Analytics Partner for Scuderia Ferrari HP

  • November 7, 2024
dotlah-smartnation-singapore-lawrence-wong
View Post
  • Data
  • Enterprise
  • Technology

Growth, community and trust the ‘building blocks’ as Singapore refreshes Smart Nation strategies: PM Wong

  • October 8, 2024
nobel-prize-popular-physics-prize-2024-figure1
View Post
  • Data
  • Featured
  • Technology

They Used Physics To Find Patterns In Information

  • October 8, 2024
goswifties_number-crunching_202405_wm
View Post
  • Data
  • Featured

Of Nuggets And Tenders. To Know Or Not To Know, Is Not The Question. How To Become, Is.

  • May 25, 2024
View Post
  • Data

Generative AI Could Offer A Faster Way To Test Theories Of How The Universe Works

  • March 17, 2024
Chess
View Post
  • Computing
  • Data
  • Platforms

Chess.com Boosts Performance, Cuts Response Times By 71% With Cloud SQL Enterprise Plus

  • March 12, 2024

Stay Connected!
LATEST
  • college-of-cardinals-2025 1
    The Definitive Who’s Who of the 2025 Papal Conclave
    • May 7, 2025
  • conclave-poster-black-smoke 2
    The World Is Revalidating Itself
    • May 6, 2025
  • 3
    Conclave: How A New Pope Is Chosen
    • April 25, 2025
  • Getting things done makes her feel amazing 4
    Nurturing Minds in the Digital Revolution
    • April 25, 2025
  • 5
    AI is automating our jobs – but values need to change if we are to be liberated by it
    • April 17, 2025
  • 6
    Canonical Releases Ubuntu 25.04 Plucky Puffin
    • April 17, 2025
  • 7
    United States Army Enterprise Cloud Management Agency Expands its Oracle Defense Cloud Services
    • April 15, 2025
  • 8
    Tokyo Electron and IBM Renew Collaboration for Advanced Semiconductor Technology
    • April 2, 2025
  • 9
    IBM Accelerates Momentum in the as a Service Space with Growing Portfolio of Tools Simplifying Infrastructure Management
    • March 27, 2025
  • 10
    Tariffs, Trump, and Other Things That Start With T – They’re Not The Problem, It’s How We Use Them
    • March 25, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    IBM contributes key open-source projects to Linux Foundation to advance AI community participation
    • March 22, 2025
  • 2
    Co-op mode: New partners driving the future of gaming with AI
    • March 22, 2025
  • 3
    Mitsubishi Motors Canada Launches AI-Powered “Intelligent Companion” to Transform the 2025 Outlander Buying Experience
    • March 10, 2025
  • PiPiPi 4
    The Unexpected Pi-Fect Deals This March 14
    • March 13, 2025
  • Nintendo Switch Deals on Amazon 5
    10 Physical Nintendo Switch Game Deals on MAR10 Day!
    • March 9, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.