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 の「Unit」型とは

Posted at

はじめに

Kotlin の Unit
値を返さない関数の戻り値型」を明示的に表すための型です。
ただし、実際には1つの値 (Unit) を返しています。

つまり、
Java の void に似ているけど、完全に同じではありません。


1. Kotlin における Unit の定義

public object Unit {
    override fun toString() = "kotlin.Unit"
}

つまり、Unit はクラスではなく シングルトン・オブジェクト
値として Unit という 唯一のインスタンスが存在します。


2. 基本例:戻り値を持たない関数

fun greet(name: String): Unit {
    println("Hello, $name!")
}

実際には戻り値を明示しなくても同じです:

fun greet(name: String) {
    println("Hello, $name!")
}

両者は完全に等価。

Kotlinでは「戻り値を書かない=Unitを返す」とみなされます。


3. Unit は “値が存在する” 型

次のようなことが可能です。

fun printMessage(): Unit {
    println("Hi")
}

val result = printMessage()
println(result) // kotlin.Unit

出力:

Hi
kotlin.Unit

つまり、Unit実際に値を持つ(ただし1つしかない)。


4. Unit は「意味のない値」を表す

  • 何か処理を行うけど、
    戻すべき“意味のある結果”がないときに使う。
  • 関数型プログラミングでは「副作用を表す戻り値」として扱われます。

5. Java の void との違い

比較項目 KotlinのUnit Javaのvoid
実体 object Unit(値あり) 値なし
null許容 Unit? 可能 void 不可
式として使用可 val x = println() 可能 ❌ 式にできない
関数型扱い () -> Unit ❌ Javaでは表せない

例:

val f: () -> Unit = { println("Hello") }
f()  // Hello

Javaでは Runnable のような特別な型を使う必要がありますが、
Kotlinでは () -> Unit として自然に扱えます。


6. Unitの実用的な使いどころ

コールバック

fun onClick(action: () -> Unit) {
    action()
}

onClick {
    println("Clicked!") // Unitを返す
}

action は「何かを実行するけど結果を返さない」関数。


map / forEach と合わせて

val list = listOf("A", "B", "C")

val result: List<Unit> = list.map { println(it) }
// 出力: A, B, C
// result = [Unit, Unit, Unit]

map は戻り値をリスト化するので、
println() の結果(Unit)が [Unit, Unit, Unit] になります。


7. Unit と Nothing の違い

比較項目 Unit Nothing
意味 値を返さない(ただし戻る) 値を返さない(戻らない)
値の存在 ✅ 1つ存在 (Unit) ❌ 存在しない
関数の挙動 正常に終了する 終了しない/例外を投げる
println() throw Exception()
戻り型の例 fun log(): Unit fun fail(): Nothing

図で見る

Any
 ├── Unit (正常終了)
 ├── Int / String / ...
 └── Nothing (戻らない)

8. Unit を返す高階関数の例

fun doSomething(action: () -> Unit) {
    println("Before")
    action()
    println("After")
}

fun main() {
    doSomething { println("Hello!") }
}

出力:

Before
Hello!
After

action() -> Unit 型の関数。
→ 結果を返さず、副作用を持つ処理を表現できます。


9. まとめ

項目 内容
型名 Unit
意味 値を返さない(が、正常に戻る)
1つ (Unit) のみ
Javaとの違い void は値なし、Unit は値あり
主な用途 副作用・コールバック・戻り値が意味を持たない処理
Nothingとの違い 「戻る」か「戻らない」かの違い

Kotlin の Unit は「何も返さない」ではなく、
「1つの意味のない値を返す」 型。

関数型プログラミングでは副作用を扱う“正規の値”として非常に重要です。

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?