3

Kotlin 与 JAVA 不同之处 - 懒懒初阳

 1 year ago
source link: https://www.cnblogs.com/fuunnyy/p/17259957.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

添加kotlin混编支持

要在Android项目中添加Kotlin混编支持,需要进行以下步骤:

  1. 在项目的 build.gradle 文件中添加以下代码:

kotlin

android {
    ...

    // 添加kotlin支持
    kotlin {
        experimental {
            coroutines "enable"
        }
    }
}

dependencies {
    ...
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
}

其中,kotlin_versioncoroutines_version 分别是 Kotlin 和 Kotlin 协程库的版本号。在 dependencies 中添加 Kotlin 库的依赖。

  1. 在项目的 module 的 build.gradle 文件中,应用 Kotlin 插件:
apply plugin: 'kotlin-android'
  1. 将 Java 代码转换为 Kotlin 代码,或者在 Kotlin 文件中编写新的代码。

  2. 在 Kotlin 文件中使用 Java 代码,或者在 Java 文件中使用 Kotlin 代码。

  3. 编译和运行项目。

这样就可以在 Android 项目中使用 Kotlin 混编了。

kotlin语言有什么特性

  1. 简洁:Kotlin减少了Java中的冗余代码,例如类型声明、空值检查和异常处理等。

  2. 可空类型:Kotlin中的类型系统通过引入可空类型,减少了空指针异常的风险。

  3. 扩展函数和属性:Kotlin允许在不改变类定义的情况下,为现有类添加新的函数和属性。

  4. Lambda表达式:Kotlin通过Lambda表达式支持函数式编程。

  5. 数据类:Kotlin提供了数据类来简化Java中的POJO类的编写。

  6. 协程:Kotlin提供了协程来支持异步编程,以及通过避免线程切换来提高应用程序的性能。

  7. 互操作性:Kotlin可以与Java代码很好地互操作,可以在现有的Java代码中使用Kotlin,也可以在Kotlin代码中使用Java库。

  8. 安全性:Kotlin通过类型系统和空值检查来提高应用程序的安全性。

  9. 交互式开发:Kotlin支持交互式开发,可以通过Kotlin REPL进行快速代码测试和验证。

  10. Android支持:Kotlin是Android官方支持的编程语言,可以用于开发Android应用程序。

好的,以下是各个特性的一个例子:

  1. 空安全:在 Kotlin 中,所有的变量都默认是不可为空的,这有助于避免空指针异常。如果想要定义一个可为空的变量,需要在变量类型后面添加 ?,例如 var str: String? = null

  2. 扩展函数:扩展函数是 Kotlin 的一项重要特性,它可以在不修改原有类定义的情况下,为类添加新的函数。例如,我们可以为 String 类型添加一个扩展函数,用于将字符串转化为整数:

    kotlin

    fun String.toIntOrNull(): Int? {
        return try {
            Integer.parseInt(this)
        } catch (e: NumberFormatException) {
            null
        }
    }
    
  3. 数据类:在 Kotlin 中,通过 data class 关键字可以快速地定义一个数据类。数据类自动重写了 equals()hashCode()toString() 等函数,并为每个属性生成了 componentN() 函数。例如:

    kotlin

    data class Person(val name: String, val age: Int)
    
    val person = Person("Alice", 20)
    println(person) // 输出:Person(name=Alice, age=20)
    
  4. Lambda 表达式:Lambda 表达式是一种匿名函数,可以作为参数传递给其他函数使用。例如,下面的代码使用 Lambda 表达式对一个列表进行过滤:

    kotlin

    val numbers = listOf(1, 2, 3, 4, 5)
    val evenNumbers = numbers.filter { it % 2 == 0 }
    println(evenNumbers) // 输出:[2, 4]
    
  5. 协程:协程是一种轻量级的线程,可以用于处理异步任务。在 Kotlin 中,可以使用协程来编写更加简洁、易读的异步代码。例如,下面的代码使用协程来实现一个延迟输出的功能:

    kotlin

    import kotlinx.coroutines.*
    
    fun main() {
        GlobalScope.launch {
            delay(1000)
            println("Hello, world!")
        }
        Thread.sleep(2000)
    }
    

data class

另外一个例子是 Kotlin 的数据类(Data Class)特性。Kotlin 的数据类是一种专门用于只保存数据的类。在 Java 中,要创建一个类只保存数据,需要手动编写构造函数、getter 和 setter 等方法。而在 Kotlin 中,只需在类名前加上 data 关键字即可自动为数据类生成以下内容:

  • 默认构造函数,构造函数中包含所有属性
  • equals() 方法
  • hashCode() 方法
  • toString() 方法,格式为类名(属性1=值1, 属性2=值2, ...)
  • copy() 方法,用于复制一个对象并修改部分属性的值

这样,使用数据类可以大大简化代码,并且让代码更易读。例如,以下是一个使用数据类的例子:

kotlin

data class User(val name: String, val age: Int)

fun main() {
    val user1 = User("Alice", 20)
    val user2 = User("Bob", 25)
    val user3 = User("Alice", 20)

    println(user1 == user2) // false
    println(user1 == user3) // true

    val user4 = user1.copy(name = "Carol")
    println(user1) // User(name=Alice, age=20)
    println(user4) // User(name=Carol, age=20)
}

在上面的例子中,我们定义了一个数据类 User,并使用它创建了几个对象。通过 == 运算符,我们可以比较两个对象是否相等。由于 User 是数据类,所以它的 equals() 和 hashCode() 方法已经被自动生成,并且按照属性的值来判断相等性。在第三个比较中,user1 和 user3 对象的属性值都相等,所以它们相等。最后,我们使用 copy() 方法创建了一个新的对象 user4,并修改了其 name 属性的值。

Null 安全
另一个Kotlin的特性是空安全(Null Safety)。在Java中,变量可以为空,这可能会导致NullPointerException(空指针异常)。但在Kotlin中,变量可以被标记为可为空或不可为空,这就意味着在编译时就可以检测到空指针异常。

例如,以下代码示例展示了Kotlin如何处理空指针异常:

javascript

var str: String? = null
var length = str?.length // 不会引起空指针异常,返回null

如果我们声明变量为不可为空(没有标记为“?”),则编译器会在编译时检测到可能的空指针异常,并在代码中强制执行空安全。这有助于减少空指针异常在运行时发生的可能性。

Extension Function

另一个例子是 Kotlin 中的扩展函数(Extension Function),它允许我们向一个已经存在的类中添加新的函数,而无需继承该类或使用装饰器模式。

例如,假设我们有一个 String 类型的变量 str,我们可以为它添加一个名为 toCamelCase() 的扩展函数,将字符串转换为驼峰格式:

kotlin

fun String.toCamelCase(): String {
    return this.split(" ").map { it.capitalize() }.joinToString("")
}

然后我们就可以通过 str.toCamelCase() 的方式来调用这个函数,而不必在 String 类中定义一个新的方法。

这样可以让我们在不改变现有类的情况下,扩展其功能,增加代码的可读性和可维护性。

kotlin的一些语法糖

System.out.print("hello world"); 
System.out.println("hello world");

Kotlin

print("hello world") 
println("hello world")
定义变量与常量常
String name = "hello world"; 
final String name = "hello world";

Kotlin

var name = "hello world" 
val name = "hello world"
null声明
String otherName; 
otherName = null;

Kotlin

var otherName : String? 
otherName = null
if (text != null) {
    int length = text.length();
}

Kotlin

text?.let {
    val length = text.length
}
// or simply
val length = text?.length
字符串拼接
String firstName = "Android"; 
String lastName = "Architect"; 
String message = "My name is: " + firstName + " " + lastName;

Kotlin

val firstName = "Android" 
val lastName = "Architect" 
val message = "My name is: $firstName $lastName"
String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";

Kotlin

val text = """
        |First Line
        |Second Line
        |Third Line
        """.trimMargin()
三元表达式
String text = x > 5 ? "x > 5" : "x <= 5";

Kotlin

val text = if (x > 5)
              "x > 5"
           else "x <= 5"
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
类型判断和转换 (声明式)
Car car = (Car) object;

Kotlin

var car = object as Car
类型判断和转换 (隐式)
if (object instanceof Car) {
   Car car = (Car) object;
}

Kotlin

if (object is Car) {
   var car = object // 自动识别
}
if (score >= 0 && score <= 300) { }

Kotlin

if (score in 0..300) { }
更灵活的case语句
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"
}
for循环
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) { }
更方便的集合操作
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")
// 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)}
void doSomething() {
   // logic here
}

void doSomething(int... numbers) {
   // logic here
}

Kotlin

fun doSomething() {
   // logic here
}

fun doSomething(vararg numbers: Int) {
   // logic here
}
带返回值的方法
int getScore() {
   // logic here
   return score;
}

Kotlin

fun getScore(): Int {
   // logic here
   return score
}

// as a single-expression function

fun getScore(): Int = score
无结束符号
int getScore(int value) {
    // logic here
    return 2 * value;
}

Kotlin

fun getScore(value: Int): Int {
   // logic here
   return 2 * value
}


// as a single-expression function

fun getScore(value: Int): Int = 2 * value
constructor 构造器
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
        }

    }
}

// another way

object Utils {

    fun getScore(value: Int): Int {
        return 2 * value
    }

}
Get Set 构造器
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)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK