Kotlin 中的 Any、Unit 、Nothing

1.官方文档

  Any    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any

  Unit    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit

  Nothing   https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-nothing.html

2.Any

2.1 源码

/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin
import kotlin.native.identityHashCode
import kotlin.native.internal.fullName
import kotlin.native.internal.ExportTypeInfo
import kotlin.native.internal.GCUnsafeCall
/**
* The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
*/
@ExportTypeInfo("theAnyTypeInfo")
public open class Any {
/**
* Indicates whether some other object is "equal to" this one. Implementations must fulfil the following
* requirements:
*
* * Reflexive: for any non-null value `x`, `x.equals(x)` should return true.
* * Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true.
* * Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true.
* * Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified.
* * Never equal to null: for any non-null value `x`, `x.equals(null)` should return false.
*
* Read more about [equality](https://kotlinlang.org/docs/reference/equality.html) in Kotlin.
*/
@GCUnsafeCall("Kotlin_Any_equals")
external public open operator fun equals(other: Any?): Boolean
/**
* Returns a hash code value for the object. The general contract of `hashCode` is:
*
* * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified.
* * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result.
*/
public open fun hashCode(): Int = this.identityHashCode()
/**
* Returns a string representation of the object.
*/
public open fun toString(): String {
val className = this::class.fullName ?: "<object>"
// TODO: consider using [identityHashCode].
val unsignedHashCode = this.hashCode().toLong() and 0xffffffffL
val hashCodeStr = unsignedHashCode.toString(16)
return "$className@$hashCodeStr"
}
}

2.2 使用

  kotlin中,所有类型默认继承自它,相当于java 中的 Object。

2.3 示例

@Test @SmallTest
fun kotlin_any(){
val list = ArrayList<Any>()
list.add(1) //ok
list.add("two") //ok
fun faa() : Any { return 1 } //ok
fun fbb() : Any { throw Exception()} //ok
fun fcc() : Any?{ throw Exception()} //ok
fun fdd() : Any?{ return null } //ok
fun <T> fee(t : T ){}
fun fff(t : Any){}
fee(1);fee("t")
fff(1);fff("t")
fun <T,Any>fgg(t : T,any: Any){}
fgg(1,1 )
fgg("e","e" )
fgg(0b1,1f )
}

3.Unit

3.1 源码

/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin
import kotlin.native.internal.ExportTypeInfo
/**
* The type with only one value: the `Unit` object.
*/
@ExportTypeInfo("theUnitTypeInfo")
public object Unit {
override fun toString() = "kotlin.Unit"
}

3.2 作用

  一个单例类,只有一个对象(Unit)。在jvm环境中,它相当于void。

3.3 示例

@Test @SmallTest
fun kotlin_unit(){
fun faa() = Unit //ok
//fun fbb() = Unit() //error
fun fcc():Unit { } //ok
}

4.Nothing

4.1 源码

/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin
/**
* Nothing has no instances. You can use Nothing to represent "a value that never exists": for example,
* if a function has the return type of Nothing, it means that it never returns (always throws an exception).
*/
public final class Nothing private constructor() {}

4.2 作用

  一个不可实例化的类型,final 且私有构造。

  • 它表示一个
  • 该值是不存在的值
  • 通常用在的函数的返回值上,表示该函数返回了一个不可能存在的值,return 什么值都错。但不影响抛异常

4.3 示例

示例1.

 @kotlin.internal.InlineOnly
 public inline fun TODO(): Nothing = throw NotImplementedError()

示例2.

@Test @SmallTest
fun kotlin_nothing(){
val list = ArrayList<Nothing>() //编译通过,但是无意义
//list.add(1) //编译失败,1是整型
//list.add(Nothing()) //Nothing 不可实例化
fun foo() : Nothing{ while(true){ } } //ok
//fun fee() : Nothing{ return 1 } //failed,1不是Nothing类型
fun fuu() : Nothing{ throw Exception()} //ok,Nothing不影响抛异常
}

 

posted @   f9q  阅读(247)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2017-01-22 printf格式化输出参数
点击右上角即可分享
微信分享提示