Using a data class for beans

Typically, we will create a number of bean classes to hold data. Kotlin introduces the concept of a data class. The following block of code shows the declaration of a data class:

data class Address(val line1: String,
val line2: String,
val zipCode: Int,
val state: String,
val country: String)

Kotlin provides a primary constructor, equals(), hashcode(), and a few other utility methods for data classes. The following lines of code shows the creation of an object using the constructors:

val myAddress = Address("234, Some Apartments",
"River Valley Street", 54123, "NJ", "USA")

Kotlin also provides a toString object:

println(myAddress)

//Address(line1=234, Some Apartments, line2=River Valley
//Street, zipCode=54123, state=NJ, country=USA)

The copy function can be used to make a copy (clone) of an existing data class object. The following code snippet shows the details:

val myFriendsAddress = myAddress.copy(line1 = "245, Some Apartments")

println(myFriendsAddress)

//Address(line1=245, Some Apartments, line2=River Valley
//Street, zipCode=54123, state=NJ, country=USA)

An object of a data class can easily be destructured. The following line of code shows the details. println makes use of string templates to print the value:

val (line1, line2, zipCode, state, country) = myAddress;

println("$line1 $line2 $zipCode $state $country");

//234, Some Apartments River Valley Street 54123 NJ USA

In this section, we looked at the important differences between Java and Kotlin. Java developers should be able to quickly pick up Kotlin skills as the fundamental concepts are similar. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset