Kotlin Class to send to Java developers

For Java developers, I will write about Kotlin classes.

Class definition

Write the class name after the class keyword. Let's define the Dog class.

class Dog {
}

Class inheritance and interface implementation are described after the colon. Let's inherit the Dog class and Animal class.

class Dog: Animal() {
}

In addition, let's implement the Walkable interface.

class Dog: Animal(), Walkable {
}

Property

Kotlin classes can have properties. This is ** a combination of Java fields, getters and setters **. Let's declare a String property called name in the Dog class. Use the var keyword.

class Dog {
    var name: String = "pochi"
}


val dog = Dog()
val aName = dog.name //Acts as a getter
dog.name = "taro" //Acts as a setter

If you want to make it read-only, use the val keyword.

class Dog {
    val name: String = "pochi"
}

val dog = Dog()
val aName = dog.name //Acts as a getter
dog.name = "taro" //Compile error!

The val keyword cannot be reassigned, so its value cannot be changed from within the class. Use the private set keyword if you want it to be changeable within the class.

class Dog {
    var name: String = "pochi"
        private set
    
    fun updateName(newName: String) {
        this.name = newName
    }
}

val dog = Dog()
dog.updateName("taro")

At this point, those who think, "No, it's the same as making a field Public in Java, right?" Are sharp. Kotlin properties are clearly separated into getters, setters and fields. For more information [here](https://qiita.com/watanave/items/1386d450f11ddf7d6c09#property and backing field)

Primary constructor

Write the Kotlin constructor in a slightly unusual position.

class Dog constructor(/*Here is the constructor*/) {
}

The constructor keyword can be omitted. It cannot be omitted when adding annotations. The constructor written in this position is called the ** primary constructor **. Even if you say a constructor, you can describe properties and a list of constructor arguments.

Define properties in the constructor

If you add the var or val keyword to the constructor argument, it becomes a property as it is.

class Dog(var name: String) {
}

↑ is synonymous with ↓.

class Dog(name: String) {
    var name: String = name
}

Initializer

The primary constructor is now able to declare constructor arguments and properties. Other processes to be performed when the class is initialized can be described in the initializer.

class Point(val x: Int, val y: Int)
class Size(val width: Int, val height: Int)

class Regtangle(val origin: Point, val size: Size) {
    val area: Int

    init {
        this.area = this.size.width * this.size.height
    }
}

val rectangle = Regtangle(30, 10, 10, 20)
println(rectangle.area)

The class Regtangle receives the origin and size from the contractor and calculates the area with the initializer.

Secondary constructor

Since there is a primary constructor, there is also a secondary constructor. You can define multiple secondary constructors. The secondary constructor must call the primary constructor after :.

class Point(val x: Int, val y: Int)
class Size(val width: Int, val height: Int)

class Regtangle(val origin: Point, val size: Size) {

    constructor(x: Int, y: Int, width: Int, height: Int): this(Point(x, y), Size(width, height))

}

Added a constructor to the class Regtangle that receives the origin and size as separate parameters.

Compare Java and Kotlin

Define the Dog class in Java. There are fields named name and age, which define getters and setters, respectively.

public class Dog {
    
    private String name;
    private int age;
    
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}

How about writing this in Kotlin?

class Dog(var name: String, var age: Int)

That's all it takes.

Recommended Posts

Kotlin Class to send to Java developers
Kotlin Class part.2 to send to Java developers
Kotlin scope functions to send to Java developers
Kotlin functions and lambdas to send to Java developers
Getting started with Kotlin to send to Java developers
Kotlin's Null safety to send to Java developers
How to use java class
How to disassemble Java class files
How to decompile java class files
[Java] How to use LinkedHashMap class
How to use class methods [Java]
Generics of Kotlin for Java developers
[Android] Convert Android Java code to Kotlin
[Java] How to use Math class
[Kotlin] 3 ways to get Class from KClass
Convert all Android apps (Java) to Kotlin
[Java] How to use the HashMap class
Introduction to kotlin for iOS developers ⑥-Kotlin creation
[Processing × Java] How to use the class
Java: How to send values from Servlet to Servlet
How to use Java Scanner class (Note)
Interoperability tips with Kotlin for Java developers
Introduction to kotlin for iOS developers ④-Type
[Java] How to use the Calendar class
Memo for migration from java to kotlin
Java class methods
java Scanner class
Java HashMap class
java (abstract class)
[Java] Nested class
Java anonymous class
About Java class
[Java] Introduction to Java
Introduction to java
[java] abstract class
[Java] Object class
Java local class
[Java] How to use FileReader class and BufferedReader class
Introduce Kotlin to your existing Java Maven Project
I want to send an email in Java.
Migrate from Java to Server Side Kotlin + Spring-boot
How to get Class from Element in Java
Initial settings for rewriting Java projects to Kotlin
How to convert a solidity contract to a Java contract class
Introduction to kotlin for iOS developers ⑤-Practical XML
Introduction to kotlin for iOS developers ③-About gradle
What I did when I converted java to Kotlin
Introduction to kotlin for iOS developers ①-Environment construction
Where Java programmers tend to trip over Kotlin
Introduction to kotlin for iOS developers ②-Project creation
How to write Java String # getBytes in Kotlin?
What Java inexperienced people did to study Kotlin
[Java] How to use Calendar class and Date class
[Java] How to use compareTo method of Date class
Mastering Kotlin ~ Convert Java File to Kotlin File Road to Graduation ~ Part 3
About class division (Java)
Changes from Java 8 to Java 11
Sum from Java_1 to 100
About Java StringBuilder class
Class to take count
[Java] About Singleton Class