今年五月份的 Google I/O 上,咱们正式向全球宣布 Kotlin-first 的这一重要理念,Kotlin 将成为 Android 开发者的首选语言。接下来的几周咱们将会为你们连载关于 Kotlin 迁移指南的系列文章,包含 Kotlin 的优点和介绍 (上篇)、迁移到 Kotlin (中篇),以及使用 Kotlin 的常见问题 (下篇),帮助开发者们顺利迁移并开始使用 Kotlin 构建 Android 应用。java
Kotlin 是一种现代的静态设置类型编程语言,能够提升开发者的工做效率,并提高开发者的工做愉悦度。android
优点 1: 可与 Java 互操做数据库
与 Android SDK 和 Java 程序语言库兼容,Kotlin 代码中能够方便调用 Java 库 (Android Studio 的 Lint 检查亦能与 Kotlin 代码互操做)。编程
优点 2: 与 IDE 工具兼容canvas
Kotlin 语言由 IntelliJ 的开发团队设计,可与 IntelliJ (以及 Android Studio) 完美搭配使用,Android Studio 为 Kotlin 提供了一流的支持,好比,您可经过内置工具来将 Java 代码转换成 Kotlin 代码。或者借助 “Show Kotlin Bytecode” 工具,您能够在学习 Kotlin 时查看等效的 Java 代码。安全
优点 3: 空安全检测bash
默认状况下,Kotlin 可避免空指针异常发生。并且能够在开发时而不是运行时发现和避免错误。网络
fun foo(p: int) { ... }
foo(null) // 编译器报错
var o: String? = ...
println(o.toLowerCase()) // 编译器报错
复制代码
△ 上面两个例子都会触发编译器报错, 从而避免了在运行时出现崩溃异步
优点 4: 更简洁的代码编程语言
Kotlin 有着更简洁明了的语法,可减小样板代码的使用。
// Java 语言类代码
public class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {...}
public String getFirstName() {...}
public void setFirstName(String firstName) {...}
public String getLastName() {...}
public void setLastName(String lastName) {...}
}
复制代码
好比上例中的数据类代码,有字段以及对应的 getter 和 setter 方法,虽然都是常规内容,但难免繁琐,并且大量的样本代码也会占用开发者的精力。咱们来看看一样的类用 Kotlin 如何编写:
// Kotlin 语言,一样的类代码
class User(
var firstName: String?,
var lastName: String?
)
复制代码
Kotlin 还支持扩展方法,能够给现有的类附加新的方法 (而不须要修改类的原始代码)。好比咱们想计算字符串内某个字符出现的次数,一般咱们这么作:
// 定义方法
fun howMany(string: String, char: Char): Int {
var count = 0
val lowerCaseLetter = char.toLowerCase()
for (i in 0 until string.length) {
if (lowerCaseLetter == string[i].toLowerCase()) count++
}
return count
}
// 计算“Elephant”里有几个“e”
val string = "Elephant"
howMany(string, 'e')
复制代码
有了扩展方法,咱们能够直接把 howMany 这个方法添加至 String 类:
// 扩展方法
fun String.howMany(char: Char): Int {
var count = 0
val lowerCaseLetter = char.toLowerCase()
for (i in 0 until length) {
if (lowerCaseLetter == this[i].toLowerCase()) count++
}
return count
}
// 执行
val string = "Elephant"
string.howMany('e')
复制代码
如此一来,咱们就直接 “问” string “你里面有几个‘e’字符” 就能够了,这更简洁、天然,可读性也大幅提高。
Kotlin 还支持指定/默认参数,这让开发者在编写方法时,不须要为不一样参数的版本另写一个方法,而是直接在同一个方法里,经过 “?” 标出可空参数,经过 “=” 给出参数的默认值便可。
// View.java
public View(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// ...
}
// 和上述内容等效的 Kotlin 代码
class View(context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0, defStyleRes: Int = 0) {
// ...
}
复制代码
△ 使用 Kotlin 仅须要定义一个构造函数便可
优点 5: 语言特性带来的进阶功能
Kotlin 也在持续为开发者带来更多高级的语言特性,协程就是一个突出的例子。
Kotlin 里的协程能够理解为从语言级别实现了异步或非阻塞编程,并在 Kotlin 1.3 中开始提供,在 Android 上使用协程能够避免下面的问题:
好比下面这个例子,使用协程时不会对主线程形成阻塞,并可提升可读性:
// 使用回调
fun getData() {
get("developer.android.google.cn") { result ->
show(result)
}
}
// 使用协程
suspend fun getData() {
val result = get("developer.android.google.cn")
show(result)
}
suspend fun get(url: String) {...}
复制代码
Android KTX
自从两年前 Android 平台开始支持 Kotlin 后,咱们一直在努力解决 Kotlin 的兼容性问题并丰富其功能,更进一步为你们带来了许多工具来进一步提升开发效率,好比 Android KTX。它是一组适用于 Android 开发的 Kotlin 扩展功能,对多种经常使用的 Android 开发流程提供简化的封装 API。
适用于动画、图形、文本等诸多领域。下面来看几个例子:
KTX: 动画
AnimatorKt 能让开发者在动画的各个阶段执行本身的操做。好比之前须要在动画结束时执行操做须要这么作:
// Animator API
fun addListener(listener: Animator.AnimatorListener!)
// 应用代码
val animator = ObjectAnimator.ofFloat(...)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
println("end!")
}
})
复制代码
而在 AnimatorKt 里,只需使用 doOnEnd 便可,代码被精简成了一行:
// AnimatorKt
inline fun Animator.doOnEnd(
crossinline action: (animator: Animator) -> Unit
)
// 应用代码
val animator = ObjectAnimator.ofFloat(...)
anim.doOnEnd { println("end!") }
复制代码
你们能够参看以下代码了解 AnimatorKt 是如何帮你们精简代码的:
inline fun Animator.doOnEnd(crossinline action: (animator: Animator) -> Unit) =
addListener(onEnd = action)
inline fun Animator.addListener(
crossinline onEnd: (animator: Animator) -> Unit = {},
crossinline onStart: (animator: Animator) -> Unit = {},
crossinline onCancel: (animator: Animator) -> Unit = {},
crossinline onRepeat: (animator: Animator) -> Unit = {}
): Animator.AnimatorListener {
val listener = object : Animator.AnimatorListener {
override fun onAnimationRepeat(animator: Animator) = onRepeat(animator)
override fun onAnimationEnd(animator: Animator) = onEnd(animator)
override fun onAnimationCancel(animator: Animator) = onCancel(animator)
override fun onAnimationStart(animator: Animator) = onStart(animator)
}
addListener(listener)
return listener
}
复制代码
KTX: Drawables 转化为位图
将可绘制对象转化为位图是很多开发者在处理 UI 时的经常使用操做,在之前须要如此操做:
// 位图 API
fun createBitmap(width: Int, height: Int, config: Bitmap.Config): Bitmap
// Canvas API
fun draw(canvas: Canvas)
// 应用代码
val (oldLeft, oldTop, oldRight, oldBottom) = bounds
drawable.setBounds(0, 0, width, height)
val bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888)
drawable.draw(Canvas(bitmap))
drawable.setBounds(oldLeft, oldTop, oldRight, oldBottom)
复制代码
但若是使用 DrawableKt,只须要以下操做便可,应用代码再次被压缩成了一行:
// DrawableKt
fun toBitmap(
width: Int = intrinsicWidth,
height: Int = intrinsicHeight,
config: Config? = null
): Bitmap
// 应用代码
d.toBitmap(width, height)
复制代码
DrawableKt 其实是使用扩展方法,将开发者须要作的操做封装了起来,从而节省了大量重复工做的时间:
fun Drawable.toBitmap(
@Px width: Int = intrinsicWidth,
@Px height: Int = intrinsicHeight,
config: Config? = null
): Bitmap {
if (this is BitmapDrawable) {
if (config == null || bitmap.config == config) {
if (width == intrinsicWidth && height == intrinsicHeight) {
return bitmap
}
return Bitmap.createScaledBitmap(bitmap, width, height, true)
}
}
val (oldLeft, oldTop, oldRight, oldBottom) = bounds
val bitmap = Bitmap.createBitmap(width, height, config ?: Config.ARGB_8888)
setBounds(0, 0, width, height)
draw(Canvas(bitmap))
setBounds(oldLeft, oldTop, oldRight, oldBottom)
return bitmap
}
复制代码
Kotlin x Jetpack
在推荐开发者使用 Kotlin 构建应用的同时,Android 团队本身也在大规模的使用 Kotlin,好比下面要跟你们介绍的在 Jetpack 库中的 Kotlin 特性的使用:
Jetpack 与协程
在 Jetpack 的下述组件库里使用了协程的特性:
Jetpack Compose
请持续关注咱们接下来时间发布的与 Kotlin 迁移指南相关的文章。
若是您对在 Android 开发中使用 Kotlin 有任何疑问或者想法,欢迎在评论区和咱们分享。
点击这里即刻使用 Kotlin 打造精彩 Android 应用