SlideShare a Scribd company logo
Data Classes in Kotlin
Tips and Tricks to use “Data Classes”
Presenter:
Naveed Ahmad
Senior Android Developer
Google Certified Associate Android Developer
https://pk.linkedIn.com/in/naveed99
sr.naveed99@gmail.com
Lesson Objectives
• Creating and using Kotlin data classes
• The advantages of data classes over regular classes
• Usage of different data class methods
• Destructuring Declarations
• Limitations of data classes in object-oriented programming
Introduction
• Concise
• Null-safe
• Interoperable
• Easy to write and understand
Why should we use Kotlin?
Data Classes
• Data classes specialize in holding data
• Compiler automatically generates the following functionality for the data
class:
1. Constructor
2. toString()
3. equals()
4. hashCode()
5. copy()
6. componentN()
Requirements for Data Classes
Every Data Class in Kotlin needs to fulfill the following requirements -
 The primary constructor must have at least one parameter
 All the parameters declared in the primary constructor need to be marked
as val or var
 Data classes cannot be abstract, open, sealed or inner
Motivation
// Kotlin Data Class
data class User( val name: String, val designation: String? )
Declaring Data Classes
• You declare data classes similar to how you declare
regular classes, except:
• The keyword data must precede the keyword class.
• The primary constructor must not be empty, and it
should contain only val or var properties.
Constructing in Data Classes
• Data classes can have two types of
constructors: primary and secondary.
• The primary constructor on a data class can
only declare properties. You can optionally
create a secondary constructor, but it must
delegate to the primary using
the this keyword.
• Here’s an example:
toString()
Imagine we have the next data class:
Customize toString method
Override toString method
Copy()
• To copy a data class but changing one or more of their properties and keeping the rest intact
• Copy function allows us to do that. Just we need to set the property that we want to change
and Kotlin will do the rest
Equals()
Equals Method:
You can also use Kotlin’s Structural equality operator == to check for equality. The == operator
internally calls the equals() method
HashCode()
ComponentN()
1 2
• Get generated corresponding to the constructor properties in their order of declaration
• Consider an example of our Customer class here we have age and name properties
declared in the primary constructor,
• 2 components methods respectively component1() and component2() will be created
Destructuring Declarations
• This is another helpful functionality that we can do with our data classes, we can get as
variables the properties of one data class
Limitations
Data classes have a few limitations when compared to regular classes:
• They have little utility other than holding data. They can’t
be open, abstract, sealed or inner classes.
• The compiler forbids manually implementing copy() and componentN() methods.
• Any parent interface or class of a data class must not have a copy() method.
Note: Another cost associated with using data classes is the increased method count in the compiled
code. While not an issue on modern Android versions, it’s something to consider when developing for
older releases.
Any Question or Confusion?

More Related Content

What's hot

Intro to Java
Intro to JavaIntro to Java
Intro to Java
karianneban
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
İbrahim Kürce
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Adil Mehmoood
 
String in java
String in javaString in java
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
ppd1961
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
C++11
C++11C++11
C++11
ppd1961
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
mcanotes
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
Prem Kumar Badri
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
arnold 7490
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Chapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsChapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutions
Saeed Iqbal
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 

What's hot (20)

Intro to Java
Intro to JavaIntro to Java
Intro to Java
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
String in java
String in javaString in java
String in java
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
OOP in C++
OOP in C++OOP in C++
OOP in C++
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
C++11
C++11C++11
C++11
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsChapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutions
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 

Similar to Data classes in kotlin by Naveed

Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
Syed Awais Mazhar Bukhari
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
Ali Aminian
 
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
Lola Burgueño
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
Muhammad Younis
 
Unit-III(Design).pptx
Unit-III(Design).pptxUnit-III(Design).pptx
Unit-III(Design).pptx
Fajar Baskoro
 
Programming with Objective-C
Programming with Objective-CProgramming with Objective-C
Programming with Objective-C
Nagendra Ram
 
Object Oriented Programming (Advanced )
Object Oriented Programming   (Advanced )Object Oriented Programming   (Advanced )
Object Oriented Programming (Advanced )
ayesha420248
 
OODPunit1.pdf
OODPunit1.pdfOODPunit1.pdf
OODPunit1.pdf
KrishMehta47
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
dkpawar
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
Max Kleiner
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
FALLEE31188
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity Framework
Mahmoud Tolba
 
Chap01
Chap01Chap01
Chap01
Jotham Gadot
 
Ef code first
Ef code firstEf code first
Ef code first
ZealousysDev
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
Rajeev Rastogi (KRR)
 
PL SQLDay Machine Learning- Hands on ML.NET.pptx
PL SQLDay Machine Learning- Hands on ML.NET.pptxPL SQLDay Machine Learning- Hands on ML.NET.pptx
PL SQLDay Machine Learning- Hands on ML.NET.pptx
Luis Beltran
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
Michael Heron
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
Amr Abd El Latief
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
 

Similar to Data classes in kotlin by Naveed (20)

Introduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTXIntroduction to Kotlin - Android KTX
Introduction to Kotlin - Android KTX
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
A Generic Neural Network Architecture to Infer Heterogeneous Model Transforma...
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
 
Unit-III(Design).pptx
Unit-III(Design).pptxUnit-III(Design).pptx
Unit-III(Design).pptx
 
Programming with Objective-C
Programming with Objective-CProgramming with Objective-C
Programming with Objective-C
 
Object Oriented Programming (Advanced )
Object Oriented Programming   (Advanced )Object Oriented Programming   (Advanced )
Object Oriented Programming (Advanced )
 
OODPunit1.pdf
OODPunit1.pdfOODPunit1.pdf
OODPunit1.pdf
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity Framework
 
Chap01
Chap01Chap01
Chap01
 
Ef code first
Ef code firstEf code first
Ef code first
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
 
PL SQLDay Machine Learning- Hands on ML.NET.pptx
PL SQLDay Machine Learning- Hands on ML.NET.pptxPL SQLDay Machine Learning- Hands on ML.NET.pptx
PL SQLDay Machine Learning- Hands on ML.NET.pptx
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 

Recently uploaded

An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
ramrag33
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
gaafergoudaay7aga
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
Madan Karki
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
TaghreedAltamimi
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 

Recently uploaded (20)

An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Data Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptxData Control Language.pptx Data Control Language.pptx
Data Control Language.pptx Data Control Language.pptx
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
integral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdfintegral complex analysis chapter 06 .pdf
integral complex analysis chapter 06 .pdf
 
Seminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptxSeminar on Distillation study-mafia.pptx
Seminar on Distillation study-mafia.pptx
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Software Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.pptSoftware Quality Assurance-se412-v11.ppt
Software Quality Assurance-se412-v11.ppt
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 

Data classes in kotlin by Naveed

  • 1. Data Classes in Kotlin Tips and Tricks to use “Data Classes” Presenter: Naveed Ahmad Senior Android Developer Google Certified Associate Android Developer https://pk.linkedIn.com/in/naveed99 sr.naveed99@gmail.com
  • 2. Lesson Objectives • Creating and using Kotlin data classes • The advantages of data classes over regular classes • Usage of different data class methods • Destructuring Declarations • Limitations of data classes in object-oriented programming
  • 3. Introduction • Concise • Null-safe • Interoperable • Easy to write and understand Why should we use Kotlin?
  • 4. Data Classes • Data classes specialize in holding data • Compiler automatically generates the following functionality for the data class: 1. Constructor 2. toString() 3. equals() 4. hashCode() 5. copy() 6. componentN()
  • 5. Requirements for Data Classes Every Data Class in Kotlin needs to fulfill the following requirements -  The primary constructor must have at least one parameter  All the parameters declared in the primary constructor need to be marked as val or var  Data classes cannot be abstract, open, sealed or inner
  • 6. Motivation // Kotlin Data Class data class User( val name: String, val designation: String? )
  • 7. Declaring Data Classes • You declare data classes similar to how you declare regular classes, except: • The keyword data must precede the keyword class. • The primary constructor must not be empty, and it should contain only val or var properties.
  • 8. Constructing in Data Classes • Data classes can have two types of constructors: primary and secondary. • The primary constructor on a data class can only declare properties. You can optionally create a secondary constructor, but it must delegate to the primary using the this keyword. • Here’s an example:
  • 9. toString() Imagine we have the next data class:
  • 11. Copy() • To copy a data class but changing one or more of their properties and keeping the rest intact • Copy function allows us to do that. Just we need to set the property that we want to change and Kotlin will do the rest
  • 12. Equals() Equals Method: You can also use Kotlin’s Structural equality operator == to check for equality. The == operator internally calls the equals() method
  • 14. ComponentN() 1 2 • Get generated corresponding to the constructor properties in their order of declaration • Consider an example of our Customer class here we have age and name properties declared in the primary constructor, • 2 components methods respectively component1() and component2() will be created
  • 15. Destructuring Declarations • This is another helpful functionality that we can do with our data classes, we can get as variables the properties of one data class
  • 16. Limitations Data classes have a few limitations when compared to regular classes: • They have little utility other than holding data. They can’t be open, abstract, sealed or inner classes. • The compiler forbids manually implementing copy() and componentN() methods. • Any parent interface or class of a data class must not have a copy() method. Note: Another cost associated with using data classes is the increased method count in the compiled code. While not an issue on modern Android versions, it’s something to consider when developing for older releases.
  • 17. Any Question or Confusion?

Editor's Notes

  1. In Slide Show mode, select the arrows to visit links.