关于android:给-Android-开发者的-Kotlin-教程一

7次阅读

共计 5323 个字符,预计需要花费 14 分钟才能阅读完成。

**segmentfault 对 mackdown 语法的反对不是很好,有些图片都显示不进去,大家能够去我的掘金查看这篇文章。

一、Kotlin 概述

<font face= 黑体 >Kotlin 是一种在 Java 虚拟机上运行的动态类型编程语言 。它次要是 JetBrains 开发团队所开发进去的编程语言。尽管 Kotlin 与 Java 语法并不兼容,但 Kotlin 被设计成能够和 Java 代码互相运作,并能够重复使用如 Java 汇合框架等现有 Java 援用的办法库。它很容易 在 Android 我的项目中代替 Java 或者同 Java 一起应用。

<font face= 黑体 >Google 在 2019 年的 Google I/O 大会上发表 Kotlin 被选为 Android 开发首选语言。

1.1、Kotlin 特点

  1. <font face= 黑体 > 简洁易用: Kotlin 中提供了大量的扩大,使得咱们的代码更加简洁,开发进去的框架更加易用;
  2. <font face= 黑体 > 平安: 防止空指针异样等整个类的谬误;
  3. <font face= 黑体 > 互操作性: 充分利用 JVM、Android 和浏览器的现有库;
  4. <font face= 黑体 > 工具敌对: 可用任何 Java IDE 或者应用命令行构建。

1.2、学习 Kotlin 的意义

  1. <font face= 黑体 > 学习正过后:目前 Kotlin 曾经成为 Android 开发的官网首选语言,当初学习 Kotlin 是正过后;
  2. <font face= 黑体 > 顺应潮流,为了将来:当初包含一二线在内的各大互联网公司都在往 Kotlin 上转,当初学习 Kotlin 不仅是顺应潮流,更是为了为了将来着想;
  3. <font face= 黑体 > 晋升开发效率:在开发效率上 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 score
var 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 9
final 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 below
for (Car car : cars) {System.out.println(car.speed);
}

// Java 8+
cars.forEach(car -> System.out.println(car.speed));

// Java 7 and below
for (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 b
val orResult   = a or b
val xorResult  = a xor b
val rightShift = a shr 2
val leftShift  = a shl 2
val unsignedRightShift = a ushr 2

三、巧用 Android Studio

3.1、为已有基于 Java 的 Android 我的项目增加 Kotlin 反对

1、通过 AS 的工具增加

<font face= 黑体 > 用 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 文件

<font face= 黑体 > 关上一个 Java 文件,而后抉择菜单栏上的 Code 选项 –> convert java file to kotlin file

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

<font face= 黑体 > 转换后:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
正文完
 0