LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第9回:Data classes

Posted at

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

Data classes
クラスプロパティデータクラスについて学んだ後、以下のJavaコードをKotlinに書き換えてください。

public class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

その後、出来上がったクラスにdata modifierを追加してください。
コンパイラはこのクラスに対して、いくつかの有用なメソッドを生成します: equals/hashCode, toString

修正前のコード

class Person

fun getPeople(): List<Person> {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}

fun comparePeople(): Boolean {
    val p1 = Person("Alice", 29)
    val p2 = Person("Alice", 29)
    return p1 == p2  // should be true
}

問題のポイント

データを保持することを主目的としたクラスを作成する場合、Kotlinでは、これらをデータクラスを使用します。
データクラスでは、いくつかの標準的な機能やユーティリティ関数が、データから機械的に導出されるます。

解答例

データクラスを定義するにはdata classとし、クラス名の後にコンストラクタを定義します。

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

fun getPeople(): List<Person> {
    return listOf(Person("Alice", 29), Person("Bob", 31))
}

fun comparePeople(): Boolean {
    val p1 = Person("Alice", 29)
    val p2 = Person("Alice", 29)
    return p1 == p2  // should be true
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0