You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
2019-08-19:Kotlin中 Unit 类型的作用以及与Java中 Void 的区别? #124
Activity
Jsondx commentedon Aug 19, 2019
第一。
dashuizhu commentedon Aug 20, 2019
绝对不意气用事。
第二,绝对不漏判任何一件坏事。
第三,绝对裁判的公正漂亮。
yizems commentedon Aug 21, 2019
https://zhuanlan.zhihu.com/p/26890263
共勉
chenqi5256969 commentedon Aug 22, 2019
1.在java中,必须指定返回类型,即void不能省略,但是在kotlin中,如果返回为unit,可以省略。
2.java中void为一个关键字,但是在kotlin中unit是一个类
103style commentedon Sep 2, 2019
@dashuizhu 蜻蜓队长前来觐见
xiaoyunfei commentedon Jun 12, 2020
Unit : Kotlin 中Any的子类, 方法的返回类型为Unit时,可以省略;
Void:Java中的方法无法回类型时使用,但是不能省略;
Nothing:任何类型的子类,编译器对其有优化,有一定的推导能力,另外其常常和抛出异常一起使用;
istudygithub commentedon Aug 24, 2026
Kotlin 的 Unit 表示函数没有有意义的返回值,它是一个真正的类型,并且只有一个值 Unit。普通 Kotlin 函数如果没有返回值,返回类型默认就是 Unit,通常可以省略。Unit 在高阶函数中也非常常见,例如 () -> Unit 表示一个没有参数、没有有意义返回值的函数。
Java 中需要区分 void 和 Void。void 是一种特殊的无返回值声明,并不是普通的对象类型;Void 则是一个引用类型,主要用于泛型等场景,它可以取 null。因此 Kotlin 的 Unit 在使用目的上类似 Java 的 void,但从类型系统角度来说,Unit 更接近一个真正的类型,而不是 Java 的 Void。