0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlin Koans やってみた 8

Last updated at Posted at 2025-02-11

Classes

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;
    }
}

その後、変換した Kotlin のクラスに data 修飾子を追加してください。
この修飾子を付けることで、コンパイラが equals / hashCode、toString などの便利なメソッドを自動生成してくれます。

解答

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

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 classes

Data classes

Kotlin のデータクラスは、主にデータを保持するために使用されます。データクラスを定義すると、コンパイラが以下のような便利なメンバ関数を自動生成してくれます。例えば、インスタンスを可読性の高い形式で出力したり、比較・コピーしたりする機能が追加されます。データクラスは、data 修飾子をつけて宣言します。

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

コンパイラは、プライマリコンストラクタで宣言されたすべてのプロパティを元に、以下のメンバを自動生成します。

  • equals() / hashCode() のペア
  • toString()(例: User(name=John, age=42)
  • 宣言順に対応する componentN() 関数
  • copy() 関数

おわりに

data class って型みたいなものだと思ってたけど、他にもできることがあるっぽくて、イメージしていたものと違ったな〜という学び。


← 前回の記事 | 次回の記事 →

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?