[毎日Kotlin] Day23. Collections Introduction

2018.02.15

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

毎日Kotlinシリーズです。

このシリーズを初めての方はこちらです。「毎日Kotlin」はじめました | Developers.IO

問題

Introduction | Try Kotlin

今日からコレクションの扱い方を学んでいきます。

This part was inspired by GS Collections Kata.

Default collections in Kotlin are Java collections, but there are lots of useful extension functions for them. For example, operations that transform a collection to another one, starting with 'to': toSet or toList.

Implement an extension function Shop.getSetOfCustomers(). The class Shop and all related classes can be found at Shop.kt.

fun Shop.getSetOfCustomers(): Set<Customer> = TODO()

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
}

狙い

ここで考えて欲しい問題の意図はなんだろうか?

コレクションの扱いの導入編です。Javaのクラスは使いつつもインターフェイスで縛ってあったり、変換の拡張関数が増えていて便利になっていたりします。

解答例

fun Shop.getSetOfCustomers(): Set<Customer> = customers.toSet()

Shopの拡張関数でCustomersをSet型で吐き出します。

data class Shop(val name: String, val customers: List<Customer>)

Shopのcustomersはval customers: Listなので、List -> Setに変換するものを作ればよいとわかります。

List -> Set に変換するメソッドがすでに用意されてあるのでcustomers.toSet()となります。

あとがき

Day24.でまたお会いしましょう。