LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第19回:Collections Introduction

Posted at

はじめに

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

過去記事はこちら

問題

Collections Introduction

拡張関数 Shop.getSetOfCustomers() を実装します。
Shop クラスと関連するすべてのクラスは、Shop.kt で見ることができます。

修正前のコード

fun Shop.getSetOfCustomers(): Set<Customer> =
        TODO()
Shop.kt
data class Shop(val name: String, val customers: List<Customer>)

data class Customer(val name: String, val city: City, val orders: List<Order>) {
    override fun toString() = "$name from ${city.name}"
}

data class Order(val products: List<Product>, val isDelivered: Boolean)

data class Product(val name: String, val price: Double) {
    override fun toString() = "'$name' for $price"
}

data class City(val name: String) {
    override fun toString() = name
}

問題のポイント

Kotlinは、Javaのコードと簡単に混ぜることができます。Kotlinのデフォルトのコレクションは、フードの下はすべてJavaのコレクションです。Javaコレクションに対するread-onlyとmutable viewsについて学びます。

  • コレクション要素にアクセスするための操作を提供する読み取り専用のインタフェース

  • 対応する読み取り専用インタフェースを書き込み操作(要素の追加、削除、更新)で拡張したmutable インタフェース

mutableコレクションを変更する場合、varである必要はないことに注意してください。
書き込み操作は同じmutableコレクションオブジェクトを変更するので、参照は変更されません。
しかし、valコレクションを再代入しようとすると、コンパイルエラーが発生します。

val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five")   // this is OK
println(numbers) // ==> [one, two, three, four, five]
//numbers = mutableListOf("six", "seven")      // compilation error

Kotlinの標準ライブラリには、コレクションをより便利に扱うための拡張関数がたくさん含まれています。例えば、「to」で始まるコレクションを別のコレクションに変換する操作:toSetやtoListなどです。

解答例

fun Shop.getSetOfCustomers(): Set<Customer> = customers.toSet()
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