Kotlin by examples: Class and Properties
Tags: android, kotlin, java
Published: 2017-02-21 15:46:26

---
title: "Kotlin by examples: Class and Properties"
published: true
description: How to learn Kotlin from Java
cover_image: 
tags: android, kotlin, java
---

I've been using Kotlin in the last few months and I'm very pleased with it! For people who don't know it, it's a language built by JetBrains (the company behind IntelliJ hence Android Studio) which compiles to the same JVM bytecode of Java.
 
It's a very modern and nice language which can be used along side Java files so doesn't require to convert an entire project.

In this blog post I'm gonna show you how to write in Kotlin what you usually write in an Android/Java project and why writing code with Kotlin is faster and nicer :=) .

Let's start with a standard definition of a class in Java:

```java
public abstract class Car {
    private String name;
    Car(String name){
        this.name = name;
    }
}
public class Ford extends Car{
    private String model;
    private String color;
    
    Ford(String model, String color){
        super("Ford");
        this.model = model;
        this.color = color;
    }
}
Ford focus = new Ford("Focus", "blue")
```
Pretty standard Java classes, we have a base abstract class called â€˜Car' and a proper class â€˜Ford' which extends Car. 
In Kotlin the same code would be:

```kotlin
abstract class Car(val name: String)

class Ford(val model: String, val color: String) : Car("Ford")

val focus = Ford("Focus", "Blue")
```

So the 15 java lines of code are just 3! In Kotlin you define constructors inline in the class definition and you have getters and setters for free based on the visibility of the fields (more on this later). 
The â€˜extends' keyword of Java is replaced by just a â€˜:' and you can also inline the constructor of the abstract class (in this case: Car(“Ford”) ).

```kotlin
Ford focus = new Ford("Focus", "blue")
focus.getName()    -> java way
val focus = Ford("Focus", "Blue")
focus.name         -> kotlin way
```

Constructors and also methods support default values, something that Java can't do:

```kotlin
class Ford(val model: String, val color: String = "Blue") : Car("Ford")
val focus = Ford("Focus")
println(focus.color)          -> prints Blue
```

It's also possible to have named field in the creation of an object, which solve one of the main problem of Java in my opinion: to understand the meaning of the fields used to create a new object. 
So let's imagine a Book class in Java with one parameter as a string:

```java
Book book = new Book("George")
```

What is “George ? is the author? the name of the book? the owner of the book? In Kotlin you can do this:

```kotlin
Book book = new Book("George")     -> Java
val book = Book("George")          -> Kotlin like Java
val book = Book(author="George")   -> more expressive way
```

Definitely better!

In Kotlin you can add the keyword â€˜data' at the beginning of a class, if you do, the compiler will add these methods for “free”:

- `equals()`/`hashCode()` pair,
- `toString()` of the form "Ford(name=Ford, model=Focus)",
- `componentN()`
- `copy()`

So with just one keyword you are getting a lot of code for free! I want to show you what `componentN()` functions means because it's something that you can't do in Java. The idea is that you can destruct the declaration of your class:

```kotlin
val focus = Ford("Focus", "Blue")
val (model, color) = focus
println("$model and $color")   -> this will print: "Focus and Blue"
```

Also the copy method is very useful to create another object from a previous one:

```kotlin
val focus = Ford("Focus", "Blue")
val yellowFocus = focus.copy(color = "Yellow")
```

In Kotlin a property can be var or val. You can think about val as a final field in Java (so it can't be modified) and var a mutable property which cannot be null, if you want to have a mutable nullable property you need to define with “<T>? expression:

```kotlin
var mutable = "mutable"
val immutable = "immutable"
mutable = "changed"                    -> 'it compiles'
immutable = "changed"                  -> 'doesn't compile'
var mutableCanBeNull: String? = null   -> 'can be null'
```

You can safely access a property that can be null with the keyword â€˜?':

```kotlin
var mutable = "mutable"
println(mutable.legnth)                 -> 'print 7'
var mutableCanBeNull: String? = null
println(mutableCanBeNull?.length)       -> 'does not crash! print null'
```

In Android most of the time you need to wait callbacks from the framework to create objects, which means they need to be defined null until the framework is ready and then every time you use those objects you need to check if it's not null.

Kotlin solves this problem with the lateinit keyword for var properties:

```kotlin
lateinit var name: String     -> 'without lateinit it does not compile'
name = "Tom"
println(name.length)
```

Please note that you don't need to do â€˜name?' but just “name' because the lateinit keyword tells the compiler that you are gonna fill the property before using it!

That's it for now! In the next post I will talk about function definitions, return types, callback and static fields.