【问题标题】:What's The Different between data class and inline class in kotlin?kotlin 中的数据类和内联类有什么区别?
【发布时间】:2021-05-30 13:49:51
【问题描述】:

kotlin 1.5.0 中,我们看到了 inline classvalue 声明,但这似乎与 data class 相似,除了我们只能在 inline class 中创建一个变量和在data class 我们可以赚更多。

但我仍然想知道inline class 的想法是什么?或者我们可以在inline classdata class 中做什么不能?

【问题讨论】:

标签: java kotlin jvm jetbrains-ide


【解决方案1】:

内联类就是将一个类型包装在一个新类中。它更像是类型别名,但它也为我们提供了类型别名所不具备的类型安全性。内联类被替换为 java 代码中的底层数据类型。

这篇文章对内联类和一些陷阱提供了很好的见解:Inline Classes and Autoboxing in Kotlin

另一方面,如果该类被设计为仅保存某些数据,那么数据类可能是一个不错的选择,

data class User(val name: String, val followersCount: Int){}

然后该类会自动为我们提供一些默认的方法。

val user = User("Youn", 5000)

// a default toString() method is implemented
println(user) // User(name=Youn, followersCount=5000)

// this is known as destructuring
// provided by the default componentN() function
val (name, followersCount) = User("Tivoli", 5)

// type of *name* is inferred to *String* and *followersCount* to *Int*
// name = Tivoli, followersCount = 5

此外,数据类中还提供了equals()copy() 的默认实现。查看更多:Data Class Kotlinlang docs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多