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?

【Kotlin】Kotlinの `infix` 関数を徹底解説 — ドットも括弧もいらない自然な関数呼び出し

Posted at

はじめに

Kotlin では infix 修飾子を使うことで、ドット(.)と括弧(())を省略して関数を呼び出すことができます。
これによりコードがまるで自然言語やDSL(Domain Specific Language)のように読みやすくなります。


基本構文

infix fun Int.times(str: String): String = str.repeat(this)

val result = 2 times "Bye "
println(result) // → "Bye Bye "

上記は通常の書き方だと以下と同じです。

val result = 2.times("Bye ")

つまり、infix は「中置記法」を使って関数呼び出しをより直感的に書けるようにするための糖衣構文(syntactic sugar)です。


infix 関数のルール

infix 関数として宣言できるのは、以下の3条件をすべて満たす関数です。

条件 内容
メンバー関数または拡張関数であること
引数が 1つ であること
vararg や デフォルト値を持たないこと

使用例①:クラス内での利用

class Person(val name: String) {
    infix fun likes(other: Person) = "${this.name} likes ${other.name}"
}

val a = Person("Anna")
val b = Person("Bob")

println(a likes b) // → Anna likes Bob

このように、オブジェクト間の関係を自然に表現できます。


使用例②:DSL 風アサーション

infix は簡易 DSL(ドメイン固有言語)を作るのにもよく使われます。

infix fun String.shouldEqual(other: String) {
    if (this != other) throw AssertionError("$this != $other")
}

"Hello" shouldEqual "Hello"  // ✅ OK
// "Hi" shouldEqual "Hello"  // ❌ AssertionError

まるでテストフレームワークのような表現になります。


使用例③:標準ライブラリでも活用されている

Kotlin の標準ライブラリにも infix 関数は多く存在します。

記述例 説明
1 to "one" Pair(1, "one") を生成
10 downTo 1 減少方向の範囲を生成
1 until 10 終端を含まない範囲を生成

例:

val map = mapOf(1 to "one", 2 to "two")

for (i in 10 downTo 1) {
    print("$i ")
}

実際にはどう動いているの?

a likes b という書き方は、コンパイラが内部的に

a.likes(b)

へ変換しています。
つまりパフォーマンス的な違いはありません
単なる構文糖衣(syntactic sugar)です。


使用例④:拡張関数 × infix

infix は拡張関数と相性抜群です。

infix fun String.concat(other: String) = this + other

println("Hello" concat "World") // → HelloWorld

infix × operator でさらに自然に!

infixoperator 修飾子と併用して、より自然な演算表現も可能です。

data class Vector(val x: Int, val y: Int)

infix operator fun Vector.plus(other: Vector) = Vector(x + other.x, y + other.y)

val a = Vector(1, 2)
val b = Vector(3, 4)

println(a plus b) // → Vector(x=4, y=6)

まとめ

項目 内容
キーワード infix
意味 中置記法で関数を呼べるようにする
条件 メンバー or 拡張関数、引数1つのみ
用途 DSL、可読性向上、自然な表現
パフォーマンス 通常呼び出しと同等(糖衣構文)

終わりに

infix は「文法上の遊び」ではなく、表現力の高い Kotlin DSL やテストコード設計の強力な武器になります。
たとえば Kotlin DSL や Compose DSL でも多用されている機能です。
一度マスターすると「自然に読めるコード」を書く感覚が身につきます。


参考

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