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?

引数指定時に条件判定

Last updated at Posted at 2024-10-16

こんにちは、新人エンジニアの三上です。

今回は、Kotlin の実装時に便利だと感じた機能を共有させていただきます。

引数

以下のような関数があるとする。
引数を渡すことで、それを「resultDto」に詰めて返す関数である。

関数
    fun createResult(
        code: String, 
        result: String? = null
    ): resultDto {
        return resultDto(
            resultCode = code,
            resultMessage = result
        )
    }

上記の関数に引数を渡す際に、条件分岐を設けることが可能である。
以下に具体的な実装を示す。

関数
    fun funcReturn(
        code: String, 
        result: String? = null, 
        resultSuccess: Boolean? = false
    ): resultDto {
        return createResult(
            code,
            if (resultSuccess == true) resultSuccess else null
        )
    }

上記のように関数の外側ではなく、引数部分に条件分岐のif 式を記載することができる。
分岐の中で関数を呼ぶ必要が無いため、コード量が削減できる。

まとめ

分岐の中で同じ関数を引数を変えて呼び出すような場合には、今回紹介した機能を使ってみて欲しい。

以上、三上でした。

(2024/10/21)ご指摘を受けて、if 文を if 式と修正しました。

0
0
2

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?