一、Kotlin 概述
Kotlin 是一种在 Java 虚拟机上运行的静态类型编程语言。它主要是 JetBrains 开发团队所开发出来的编程语言。虽然Kotlin 与 Java 语法并不兼容,但Kotlin 被设计成可以和 Java 代码相互运作,并可以重复使用如 Java 集合框架等现有 Java 引用的方法库。它很容易在 Android 项目中替代 Java 或者同 Java 一起使用。
Google 在的 Google I/O 大会上宣布 Kotlin 被选为 Android 开发首选语言。
1.1、Kotlin 特点
简洁易用: Kotlin中提供了大量的扩展,使得我们的代码更加简洁,开发出来的框架更加易用;安全: 避免空指针异常等整个类的错误;互操作性: 充分利用 JVM、Android 和浏览器的现有库;工具友好: 可用任何 Java IDE 或者使用命令行构建。1.2、学习 Kotlin 的意义
学习正当时:目前Kotlin已经成为Android开发的官方首选语言,现在学习Kotlin是正当时;顺应潮流,为了未来:现在包括一二线在内的各大互联网公司都在往Kotlin上转,现在学习Kotlin不仅是顺应潮流,更是为了为了未来着想;提升开发效率:在开发效率上Kotlin开发要比Java高很多。二、Kotlin 与 Java 比较
1、打印日志
Java
System.out.print("hello world");System.out.println("hello world");
Kotlin
print("hello world")println("hello world")
2、定义常量与变量
Java
String name = "hello world";final String name = "hello world";
Kotlin
var name = "hello world"val name = "hello world"
3、null 声明
Java
String name;name = null;
Kotlin
var name : String?name = null
4、空判断
Java
if (text != null) {int length = text.length();}
Kotlin
text?.let {val length = text.length}// 或者val length = text?.length
5、字符串拼接
Java
String firstName = "Android";String lastName = "enginner";String message = "My name is: " + firstName + " " + lastName;
Kotlin
val firstName = "Android"val lastName = "enginner"val message = "My name is: $firstName $lastName"
6、三元表达式
Java
String text = x > 5 ? "x > 5" : "x <= 5";
Kotlin
val text = if (x > 5)"x > 5"else "x <= 5"
7、多重条件
Java
if (score >= 0 && score <= 300) {}
Kotlin
if (score in 0..300) {}
8、更灵活的 case 语句
Java
int score = // some score;String grade;switch (score) {case 10:case 9:grade = "Excellent";break;case 8:case 7:case 6:grade = "Good";break;case 5:case 4:grade = "OK";break;case 3:case 2:case 1:grade = "Fail";break;default:grade = "Fail";}
Kotlin
var score = // some scorevar grade = when (score) {9, 10 -> "Excellent"in 6..8 -> "Good"4, 5 -> "OK"in 1..3 -> "Fail"else -> "Fail"}
9、for 循环
Java
for (int i = 1; i <= 10 ; i++) {}for (int i = 1; i < 10 ; i++) {}for (int i = 10; i >= 0 ; i--) {}for (int i = 1; i <= 10 ; i+=2) {}for (int i = 10; i >= 0 ; i-=2) {}for (String item : collection) {}for (Map.Entry<String, String> entry: map.entrySet()) {}
Kotlin
for (i in 1..10) {}for (i in 1 until 10) {}for (i in 10 downTo 0) {}for (i in 1..10 step 2) {}for (i in 10 downTo 0 step 2) {}for (item in collection) {}for ((key, value) in map) {}
10、更方便的集合操作
Java
final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);final Map<Integer, String> keyValue = new HashMap<Integer, String>();map.put(1, "Android");map.put(2, "Ali");map.put(3, "Mindorks");// Java 9final List<Integer> listOfNumber = List.of(1, 2, 3, 4);final Map<Integer, String> keyValue = Map.of(1, "Android",2, "Ali",3, "Mindorks");
Kotlin
val listOfNumber = listOf(1, 2, 3, 4)val keyValue = mapOf(1 to "Android",2 to "Ali",3 to "Mindorks")
11、遍历
Java
// Java 7 and belowfor (Car car : cars) {System.out.println(car.speed);}// Java 8+cars.forEach(car -> System.out.println(car.speed));// Java 7 and belowfor (Car car : cars) {if (car.speed > 100) {System.out.println(car.speed);}}// Java 8+cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));
Kotlin
cars.forEach {println(it.speed)}cars.filter {it.speed > 100 }.forEach {println(it.speed)}
12、方法定义
Java
void doSomething() {// logic here}void doSomething(int... numbers) {// logic here}
Kotlin
fun doSomething() {// logic here}fun doSomething(vararg numbers: Int) {// logic here}
13、constructor 构造器
Java
public class Utils {private Utils() {// This utility class is not publicly instantiable}public static int getScore(int value) {return 2 * value;}}
Kotlin
class Utils private constructor() {companion object {fun getScore(value: Int): Int {return 2 * value}}}// 或者object Utils {fun getScore(value: Int): Int {return 2 * value}}
14、Get Set 构造器
Java
public class Developer {private String name;private int age;public Developer(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
Kotlin
data class Developer(val name: String, val age: Int)
15、操作符
Java
final int andResult = a & b;final int orResult = a | b;final int xorResult = a ^ b;final int rightShift = a >> 2;final int leftShift = a << 2;final int unsignedRightShift = a >>> 2;
Kotlin
val andResult = a and bval orResult = a or bval xorResult = a xor bval rightShift = a shr 2val leftShift = a shl 2val unsignedRightShift = a ushr 2
三、巧用 Android Studio
3.1 、为已有基于 Java 的 Android 项目添加Kotlin 支持
1、通过 AS 的工具添加
用 Android Studio 打开已有的 Android 项目,然后菜单栏上的Tools
选项 -->Kotlin
-->configure kotlin in project
2、手动添加
project/build.gradle
buildscript {// add+ ext.kotlin_version = '1.3.61'repositories {google()jcenter()}dependencies {classpath 'com.android.tools.build:gradle:3.5.3'// add+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"}}
app/build.gradle
apply plugin: 'com.android.application'// add+ apply plugin: 'kotlin-android-extensions'// add+ apply plugin: 'kotlin-android'...dependencies {...// add+ implementation "androidx.core:core-ktx:+"// add+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"}repositories {mavenCentral()}
3.2 、将 Java 文件转成 Kotlin 文件
打开一个 Java 文件,然后选择菜单栏上的Code
选项 -->convert java file to kotlin file
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}}
转换后:
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)}}