LoginSignup
1

More than 1 year has passed since last update.

Kotlinのスコープ関数の勘所

Posted at

はじめに

val user = User().apply {
    name = "kotlin"
    age = 22
}

みなさん、Kotlinのスコープ関数は好きですか?私は大好きです😍

スコープ関数が好きな理由はいくつかあります。

  • コードのまとまりがわかりやすくなる(可読性UP)
  • コードの文脈を表現できる

とりわけ「コードの文脈を表現できる」という点が優れていて、スコープ関数の名前(letalso)だけで、どんなコードがまとめられているのか推測することができます。

スコープ関数は大変便利なものですが、用法を守らないと却ってコードの文脈がわかりにくくなってしまいます。
しかしながら、スコープ関数を使い分けるのはなかなか難しいものです。

そこで本記事では、私がスコープ関数をそこそこ使い分けれるようになった時に感じた勘所をご紹介します。
最後に、私がAndroid開発でよく書くスコープ関数のコード例を示します。

スコープ関数の勘所

スコープ関数の使い分けを知る

公式ドキュメントにしっかり利用例が書いてあります。
こちらのページを常に参照していればOKだと思います。
https://kotlinlang.org/docs/reference/scope-functions.html#function-selection

スコープ関数の戻り値が何になるか知る

スコープ関数は戻り値の違いで2つに大別できます。

戻り値がオブジェクトのまま 戻り値はラムダ式の結果
apply, also let, run with

同じことがこのページにも書いています。
https://kotlinlang.org/docs/reference/scope-functions.html#function-selection

コード例

RecyclerViewの設定

RecyclerViewadapterlayoutAdapterを設定する時は、「設定する」という文脈でapplyを使うのが良いと思います。

class HomeFragment : Fragment(R.layout.fragment_home) {

    private val userAdapter = UserAdapter() // RecyclerView.Adapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val binding = FragmentHomeBinding.bind(view)
        binding.recyclerView.apply {
            adapter = userAdapter
            layoutManager = LinearLayoutManager(context)
        }
}

ViewBinding

ViewBindingを使ってTextViewにテキストを入れたりImageViewに画像を表示させたりするときは、「ViewBindingに関する処理をまとめる」という文脈でwithを使うと良いと思います。

class HomeFragment : Fragment(R.layout.fragment_home) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val binding = FragmentHomeBinding.bind(view)
        with(binding) {
            usename.text = "USERNAME"
            icon.load("https://...") // coilライブラリ
        }
}

Date型から文字列に変換して代入する

ある変数を引数にとって別の値を返したい時には、letを使うといいと思います。
以下のコードでは、letを使うことでdateNonNullの引数として扱い、文字列として返すような関数が作れています。

@BindingAdapter("date_text")
fun TextView.dateToText(date: Date?) {
    val text = date?.let {
        SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.US)
            .apply { timeZone = TimeZone.getDefault() }
            .format(it)
    }.orEmpty()
    setText(text)
}

まとめ

Kotlinのスコープ関数の勘所

  • スコープ関数の使い分けを知る
  • スコープ関数の戻り値が何になるか知る

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
What you can do with signing up
1