🤖

【Kotlin学習記3】Kotlinはドキュメントを読むのが楽しい

に公開

簡単なTodoアプリの作成に挑戦しています。

AndroidStudioで関数の定義元にらくらくジャンプできるので、標準関数などのソースコードを読むのが楽で、色々な発見がありました。

関数にカーソルを当てた時に出てくる、関数シグネチャの意味が初めは理解できませんでした。

よく出てくる文法としては、拡張関数でしょうか。

例えば、リスト表示をするためにLazyColumnコンポーネントを使いました。それの引数の最後にある、

content: LazyListScope.() -> Unitについて、まずKotlinでは最後の引数がラムダ関数だった場合、引数の()の中でなく、{}にその要素を記述して良いらしいです。

最初、この仕組みを知らなかったので、戸惑いました。

では、LazyListScope.() -> Unitはどのような意味でしょうか?

LazyListScope をレシーバに持つラムダを受け取るという意味です。では、レシーバとは何か?

LazyListScope をレシーバにするとは、ラムダの内部で暗黙的に LazyListScope のメンバ関数や拡張関数を直接呼び出せるようにする、という意味です。LazyColumn { … } の { … } 部分では LazyListScope がレシーバとして渡されているので、items(...) や item { … } を「レシーバなし」で書けます。実際には this.items(...) を呼んでいるのと同じ状態で、this が LazyListScope になっているイメージです。

そこで、どのようなLazyListScopeのメンバ関数や拡張関数が呼び出せるのかを調べるために、LazyListScopeの定義元にジャンプしました。


interface LazyListScope {
		// (中略)
    /**
     * Adds a [count] of items.
     *
     * @param count the items count
     * @param key a factory of stable and unique keys representing the item. Using the same key for
     *   multiple items in the list is not allowed. Type of the key should be saveable via Bundle on
     *   Android. If null is passed the position in the list will represent the key. When you
     *   specify the key the scroll position will be maintained based on the key, which means if you
     *   add/remove items before the current visible item the item with the given key will be kept
     *   as the first visible one. This can be overridden by calling 'requestScrollToItem' on the
     *   'LazyListState'.
     * @param contentType a factory of the content types for the item. The item compositions of the
     *   same type could be reused more efficiently. Note that null is a valid type and items of
     *   such type will be considered compatible.
     * @param itemContent the content displayed by a single item
     */
    fun items(
        count: Int,
        key: ((index: Int) -> Any)? = null,
        contentType: (index: Int) -> Any? = { null },
        itemContent: @Composable LazyItemScope.(index: Int) -> Unit,
    ) {
        error("The method is not implemented")
    }
		// (中略)
	}
	
inline fun <T> LazyListScope.items(
    items: List<T>,
    noinline key: ((item: T) -> Any)? = null,
    noinline contentType: (item: T) -> Any? = { null },
    crossinline itemContent: @Composable LazyItemScope.(item: T) -> Unit,
) =
    items(
        count = items.size,
        key = if (key != null) { index: Int -> key(items[index]) } else null,
        contentType = { index: Int -> contentType(items[index]) },
    ) {
        itemContent(items[it])
    }

なるほどと思いました。ファイルの前半では、LazyListScopeのインターフェースを定義しています。

その中に、itemsメソッドが定義されています。

そしてインターフェースの定義が終わると、その下に、拡張関数の定義があります。inline fun <T> LazyListScope.items()={}

keyは一意のものを割り当てないといけないようです。私は最初、引数のkeyを指定しなかったので、内部で初期値nullとして扱われました。実際のTodoリストの挙動としては、削除ボタンを押すとそのアイテムとは別のアイテムが削除されるという、チグハグな挙動になりました。

とりあえず、以下のライブラリを使ってユニークIDを生成して、それをkeyに割り当てようと思いました。

https://github.com/benasher44/uuid

どうすればこのパッケージを使えるように出来るのかがわかりませんでした。jsならnpm install. phpならcomposer installでインストールしていました。おそらくKotlinも同じような流れだと思いつつ、Gradleについて勉強しました。

Gradleはビルド、テスト、デプロイをビルドスクリプトをもとに、自動的に行うビルド自動化ツールらしい。

Gradleをざっくり理解するために、下記のサイトを参考にさせていただきました。

https://vegcale.com/2023/12/09/what-is-gradle/

ビルドやデプロイだけでなく、テストも一緒にできるのは、機能が豊富だなと思いました。PHPならComoserの他に、テスト自動化ツールであるPHPUnitが必要でした。

Discussion