Inline value classes
有时候,业务逻辑需要围绕某种类型创建包装器。然而,由于额外的堆内存分配问题, 它会引入运行时的性能开销。此外,如果被包装的类型是原生类型,性能的损失是很糟糕的, 因为原生类型通常在运行时就进行了大量优化,然而他们的包装器却没有得到任何特殊的处理。
为了解决这类问题,Kotlin 引入了一种被称为内联类的特殊类。 Inline classes are a subset of value-based classes. They don’t have an identity and can only hold values.
To declare an inline class, use the value modifier before the name of the class:
1. value class Password(private val s: String)
To declare an inline class for the JVM backend, use the value modifier along with the @JvmInline annotation before the class declaration:
1. // For JVM backends
2. @JvmInline
3. value class Password(private val s: String)
内联类必须含有唯一的一个属性在主构造函数中初始化。在运行时, 将使用这个唯一属性来表示内联类的实例(关于运行时的内部表达请参阅下文):
1. // 不存在 'Password' 类的真实实例对象
2. // 在运行时,'securePassword' 仅仅包含 'String'
3. val securePassword = Password("Don't try this in production")
这就是内联类的主要特性,它灵感来源于 inline 这个名称:类的数据被内联到该类使用的地方(类似于内联函数中的代码被内联到该函数调用的地方)。
成员
内联类支持普通类中的一些功能。特别是,内联类可以声明属性与函数, have an init block and secondary constructors:
1. @JvmInline
2. value class Person(private val fullName: String) {
3. init {
4. require(fullName.isNotEmpty()) {
5. "Full name shouldn't be empty"
6. }
7. }
9. constructor(firstName: String, lastName: String) : this("$firstName $lastName") {
10. require(lastName.isNotBlank()) {
11. "Last name shouldn't be empty"
12. }
13. }
15. val length: Int
16. get() = fullName.length
18. fun greet() {
19. println("Hello, $fullName")
20. }
21. }
23. fun main() {
24. val name1 = Person("Kotlin", "Mascot")
25. val name2 = Person("Kodee")
26. name1.greet() // greet` 函数会作为一个静态方法被调用
27. println(name2.length) // 属性的 getter 会作为一个静态方法被调用
28. }
Inline class properties cannot have backing fields. They can only have simple computable properties (no lateinit/delegated properties).
继承
内联类允许去继承接口
1. interface Printable {
2. fun prettyPrint(): String
3. }
5. @JvmInline
6. value class Name(val s: String) : Printable {
7. override fun prettyPrint(): String = "Let's $s!"
8. }
10. fun main() {
11. val name = Name("Kotlin")
12. println(name.prettyPrint()) // 仍然会作为一个静态方法被调用
13. }
禁止内联类参与到类的继承关系结构中。这就意味着内联类不能继承其他的类而且始终是 final 的。
表示方式
在生成的代码中,Kotlin 编译器为每个内联类保留一个包装器。内联类的实例可以在运行时表示为包装器或者基础类型。这就类似于 Int 可以表示为原生类型 int 或者包装器 Integer。
为了生成性能最优的代码,Kotlin 编译更倾向于使用基础类型而不是包装器。 然而,有时候使用包装器是必要的。一般来说,只要将内联类用作另一种类型, 它们就会被装箱。
1. interface I
3. @JvmInline
4. value class Foo(val i: Int) : I
6. fun asInline(f: Foo) {}
7. fun <T> asGeneric(x: T) {}
8. fun asInterface(i: I) {}
9. fun asNullable(i: Foo?) {}
11. fun <T> id(x: T): T = x
13. fun main() {
14. val f = Foo(42)
16. asInline(f) // 拆箱操作: 用作 Foo 本身
17. asGeneric(f) // 装箱操作: 用作泛型类型 T
18. asInterface(f) // 装箱操作: 用作类型 I
19. asNullable(f) // 装箱操作: 用作不同于 Foo 的可空类型 Foo?
21. // 在下面这里例子中,'f' 首先会被装箱(当它作为参数传递给 'id' 函数时)然后又被拆箱(当它从'id'函数中被返回时)
22. // 最后, 'c' 中就包含了被拆箱后的内部表达(也就是 '42'), 和 'f' 一样
23. val c = id(f)
24. }
因为内联类既可以表示为基础类型有可以表示为包装器,引用相等对于内联类而言毫无意义,因此这也是被禁止的。
Inline classes can also have a generic type parameter as the underlying type. In this case, the compiler maps it to Any? or, generally, to the upper bound of the type parameter.
1. @JvmInline
2. value class UserId<T>(val value: T)
4. fun compute(s: UserId<String>) {} // compiler generates fun compute-<hashcode>(s: Any?)
名字修饰
由于内联类被编译为其基础类型,因此可能会导致各种模糊的错误,例如意想不到的平台签名冲突:
1. @JvmInline
2. value class UInt(val x: Int)
4. // 在 JVM 平台上被表示为'public final void compute(int x)'
5. fun compute(x: Int) { }
7. // 同理,在 JVM 平台上也被表示为'public final void compute(int x)'!
8. fun compute(x: UInt) { }
为了缓解这种问题,一般会通过在函数名后面拼接一些稳定的哈希码来修饰函数名。 因此,fun compute(x: UInt) 将会被表示为 public final void compute-<hashcode>(int x),以此来解决冲突的问题。
Calling from Java code
You can call functions that accept inline classes from Java code. To do so, you should manually disable mangling: add the @JvmName annotation before the function declaration:
1. @JvmInline
2. value class UInt(val x: Int)
4. fun compute(x: Int) { }
6. @JvmName("computeUInt")
7. fun compute(x: UInt) { }
内联类与类型别名
初看起来,内联类似乎与类型别名非常相似。实际上,两者似乎都引入了一种新的类型,并且都在运行时表示为基础类型。
然而,关键的区别在于类型别名与其基础类型(以及具有相同基础类型的其他类型别名)是赋值兼容的,而内联类却不是这样。
换句话说,内联类引入了一个真实的新类型,与类型别名正好相反,类型别名仅仅是为现有的类型取了个新的替代名称 (别名):
1. typealias NameTypeAlias = String
3. @JvmInline
4. value class NameInlineClass(val s: String)
6. fun acceptString(s: String) {}
7. fun acceptNameTypeAlias(n: NameTypeAlias) {}
8. fun acceptNameInlineClass(p: NameInlineClass) {}
10. fun main() {
11. val nameAlias: NameTypeAlias = ""
12. val nameInlineClass: NameInlineClass = NameInlineClass("")
13. val string: String = ""
15. acceptString(nameAlias) // 正确: 传递别名类型的实参替代函数中基础类型的形参
16. acceptString(nameInlineClass) // 错误: 不能传递内联类的实参替代函数中基础类型的形参
18. // And vice versa:
19. acceptNameTypeAlias(string) // 正确: 传递基础类型的实参替代函数中别名类型的形参
20. acceptNameInlineClass(string) // 错误: 不能传递基础类型的实参替代函数中内联类类型的形参
21. }
Inline classes and delegation
Implementation by delegation to inlined value of inlined class is allowed with interfaces:
1. interface MyInterface {
2. fun bar()
3. fun foo() = "foo"
4. }
6. @JvmInline
7. value class MyInterfaceWrapper(val myInterface: MyInterface) : MyInterface by myInterface
9. fun main() {
10. val my = MyInterfaceWrapper(object : MyInterface {
11. override fun bar() {
12. // body
13. }
14. })
15. println(my.foo()) // prints "foo"
16. }
