What is great in Kotlin? Data class!

article-2202821-150213ff000005dc-976_634x391

One of the great things in Kotlin is the Data class.

When you are working with a data class, you spend a lot of time to write getters and setters and equal operator and so on…

Kotlin show all his power in this situations, in fact you can write only something like this:


data class Person (val name: String, val age:Int)  //Formattare

And.. it’s all!

If you want to add a new parameter, you can add and then all it’s ok! You don’t waste your time to write new getters and setters and modify the equal operator.

Now, we want to use this data class: it’s so simple!


fun getUser(): User {
    return User("Alex", 1)
}

fun main(args: Array<String>) {
    val user = getUser()
    println("hello my name is  ${user.name}, and I'm ${user.id}")

    // or

    val (name, id) = getUser()
    println("hello my name is $name, and I'm $id")

    // or

    println("hello my name is ${getUser().component1()}, and I'm ${getUser().component2()}")
}

I think this is a cool feature of kotlin because, in this way, the code is less verbose than other lenguages.

Advertisements

One thought on “What is great in Kotlin? Data class!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s