1
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?

More than 3 years have passed since last update.

Kotlinは引数の初期化に引数が使える

Posted at

ギョームで使って便利だなーと思ったので備忘録。

Kotlinは引数の初期化に引数が使えます。

data class A(
  val a: String,
  val aa: String = a.repeat(2),
)
Welcome to Kotlin version 1.5.10 (JRE 15.0.2+7)
Type :help for help, :quit for quit
>>> data class A(val a: String, val aa: String = a.repeat(2))
>>> println(A(a = "hello "))
A(a=hello , aa=hello hello )

面白いね!

役立ったところ

(一部脚色してます)性別や職種に応じてデフォルトの敬称(Honorific)を設定するのに使いました。

data class User(
  val name: String = "",
  val sex: Sex = Sex(),
  val occupation: Occupation = Occupation(),
  val honorific: String = honorific(sex, occupation),
) {
  companion object {
    private fun honorific(
      sex: Sex,
      occupation: Occupation,
    ): String {
      return when {
        (なんか条件1) -> "さん"
        (なんか条件2) -> "くん"
      }
    }
  }
}
1
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
1
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?