本文共 4943 字,大约阅读时间需要 16 分钟。
据我们所知,有‘已知的已知’,有些事,我们知道我们知道;我们也知道,有‘已知的未知’,也就是说,有些事,我们现在知道我们不知道
-- 唐纳德·拉姆斯菲尔德
我已经使用Kotlin差不多两年了,我最开始时为了技术演讲将它用于一个实验项目。你还记得那个时候 Kotlin 使用的是 traits 而不是 interfaces ? 从写下第一行代码开始,我就知道这门语言将改变我的生活,你知道发生了什么吗?我预测的完全正确。
知识使你变得更强大,这就是为什么世界的大多数成功的工程师总是在学习新的东西。这里是我整理的5条关于 Kotlin 不那么有名的特性,我希望你会发现其中至少有3条值得你去了解。
在 Kotlin 中,import 是提供给编译器使用的,有了 import 你可以通过不完整的名称来命名类。但是如果有名称冲突的话会发生什么事情?会发生悲剧!
package com.code.sliski.userinfoscreen.uiimport ...import android.view.View // Conflictclass UserInfoFragment : Fragment(), com.code.sliski.userinfoscreen.ui.View { // Conflict override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): View = // Conflict inflater.inflate(user_info_fragment, container, false)}interface View // Conflict
就我个人而言,我讨厌在代码中使用完整的包名,因为那样会降低代码的可读性和清晰度。在 Python 中,你可以命名 import 来解决这样的冲突问题,Kotlin 同样也支持这一功能❤。
import android.view.View as AndroidView // Named importclass UserInfoFragment : Fragment(), View { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, state: Bundle?): AndroidView = // Using named import}
Companion object 是用来替换静态成员的。它不仅可以用来声明静态属性,并且还可以给它命名。怎么实现?我们一起来看这个示例:
// Using in JavaCustomButton button = new CustomButton(context);button.setVisibility(CustomButton.Companion.getGONE());// Using in Kotlinval button = CustomButton(context)button.visibility = CustomButton.VISIBLEclass CustomButton(context: Context?) : View(context) { companion object { // Visibility val GONE = 1 val VISIBLE = 2 val INVISIBLE = 3 }}
Kotlin 默认会为每一个 companion object 创建一个静态匿名类 Companion。这就是为什么在 Java 代码中需要通过 CustomButton.Companion 来访问其静态成员(在 Kotlin 中你也可以这样访问,但是没有必要)。Kotlin 允许你将 companion object 的默认名称修改为任意名称。 将上面的代码重构一下:
// Using in JavaCustomButton button = new CustomButton(context);button.setVisibility(CustomButton.Visibility.getGONE());...class CustomButton(context: Context?) : View(context) { companion object Visibility { val GONE = 1 val VISIBLE = 2 val INVISIBLE = 3 }}
这里最大的缺陷是 Kotlin 不支持单个类拥有多个 companion object。 这对于分组静态属性非常有用。
val button = CustomButton(context)button.visibility = CustomButton.Visibility.VISIBLEbutton.foregroundGravity = CustomButton.ForegroundGravity.LEFTclass CustomButton(context: Context?) : View(context) { companion object Visibility { val VISIBLE = 1 val INVISIBLE = 2 } companion object ForegroundGravity { val LEFT = 1 val RIGHT = 2 }}
这段代码不能通过编译,因为 Kotlin 仅支持一个类拥有一个 companion object
我相信你使用过函数引用,但是你尝试过用他们来组合函数吗?想象一下你需要将一组价格通过税费、打折和四舍五入后映射成另外一组价格。使用普通的方法你将写出类似这样的代码:
val prices = listOf(21.8, 232.5, 231.3)prices.map(::taxed) .map(::discounted) .map(::rounded)fun taxed(value: Double): Double = value * 1.4fun discounted(value: Double): Double = value * 0.9fun rounded(value: Double): Double = Math.round(value).toDouble()
这个例子是为了演示函数组合,所以请不要忽视它。 Abracadabra
val prices = listOf(21.8, 232.5, 231.3)val taxedDiscountedRounded = compose(::taxed, ::discounted, ::rounded)prices.map(taxedDiscountedRounded)fun compose(f: (A) -> A, g: (A) -> A, h: (A) -> B): (A) -> B = { x -> h(g(f(x))) }fun taxed(value: Double): Double = value * 1.4fun discounted(value: Double): Double = value * 0.9fun rounded(value: Double): Double = Math.round(value).toDouble()
函数组合不仅仅使你的代码更简洁,还会使你的代码运行的更快。一旦你理解了函数组合,你几乎可以组合出任何东西。
扩展函数是 Kotlin 最具吸引力的特性之一,但是在 Java 代码中使用扩展函数非常头疼。代码非常丑陋,并且看起来和调用一个静态方法没什么两样。
// Main.javapublic static void main(String[] args) { String name = null; AnyKt.ifNull(name, new Function1
Kotlin 会生成一个具有静态方法的 AnyKt 类,所以你可在 Java 代码中使用它。有一种方法可以修改生成的类的名称,从而获得更好的可读性。
// Main.javapublic static void main(String[] args) { String name = null; Nullcheck.ifNull(name, new Function1
Kotlin处理代理的方式非常引人注目的,如果你不是很了解,你应该先读一下我的另一篇文章。
除了 “class delegation” 还有一种有趣的机制称为 “delegated properties”。 这种机制用于 lazy 属性的初始化。如果有一个场景是你想拦截对一个属性的赋值并且“否决(veto)”它该怎么办呢?有任何简洁的方式可以实现这个需求吗?有!
var price: Double by Delegates.vetoable(0.0) { prop, old, new -> validate(new)}fun validate(price: Double) : Boolean { // Validation checks}
这个示例展示了内置 vetoable 代理的使用。传递给 vetoable 的 Lambda 表达式会在将新值赋值给 property之前调用。如果 lambda 返回的结果是 false,你就可“否决”这次赋值,但是如果你想通过那么就需要返回 true。
本文译自
1人点赞
转载地址:http://rbfcb.baihongyu.com/