Dart VS Kotlin

2,553 阅读1分钟

dart 其实跟kotlin很像,而kotlin很早也被谷歌列为第一开发语言,那为什么没有选择kotlin而使用了dart呢, 我也说不上来O(∩_∩)O~~。

下面对比下dart vs kotlin:

Hello world

Kotlin

println("Hello, world!")

Dart

print("Hello, world!");

变量&常量

Kotlin

var myVar = 1
myVar = 2
val myConstant = 5

Dart

var myVar = 1;
myVar = 2;
const myConstant = 5;

显示类型

Kotlin

val explicitVar: Int = 7

Dart

int explicitVar = 7;

String拼接

Kotlin

val apples = 3
val oranges = 3
val message = "I have ${apples + oranges} fruits"

Dart

var apples = 3;
var oranges = 3;
var message = "I have ${apples + oranges} fruits";

数组

Kotlin

val fruits = arrayOf("apple", "orange", "banana")

Dart

var fruits = ["apple", "orange", "banana"];

Maps

Kotlin

    val basket = mutableMapOf(
        "apple" to 3,
        "orange" to 2
    )

    basket["apple"] = 5

Dart

    var basket = {
        "apple": 3,
        "orange": 2,
    };

    basket["apple"] = 5;

函数

Kotlin

    fun greet(name: String): String {
        return "Hello $name"
    }

    greet("Bob")

Dart

    String greet(String name) {
        return "Hello $name";
    }

    greet("Bob");

可选参数

Kotlin

    fun addIntro(title: String, subtitle: String = "No subtitle", bold: Boolean = true) {
        // ...
    }

    addIntro("Title")
    addIntro("Title", "My subtitle")
    addIntro("Title", "My subtitle", false)

Dart

    void addIntro(String title, [String subtitle, bool bold]) {
        // ...
    }

    addIntro("Title");
    addIntro("Title", "My subtitle");
    addIntro("Title", "My subtitle", false);

Kotlin

    class Foo {
        private var bar = 0
    }

Dart

    class Foo {
        int _bar = 0; // underscore marks the field as private
        
        int get bar => _bar;
        set bar(int val) => _bar = val;
    }

类型检查

Kotlin

    val obj = "string"
    if (obj is String) {
        print(obj.length)
    }

Dart

    var obj = "string";
    if (obj is String) {
        print(obj.length);
    }

空安全

Kotlin

    var a: String = "abc"
    a = null // compilation error
    var b: String? = "abc"
    b = null // ok
    val length = b?.length // length will be null

Dart

    var a = "abc";
    a = null;
    var length = a.length; // NPE
    length = a?.length; // length will be null

数据类 Data classes

Kotlin

    // this will also generate equals, hashCode, toString methods
    data class Box(val width: Int, val height: Int)

Dart Dart没有这个特性,但是我们可以通过代码生成的问题。但是我们可以通过built_value包来生成。

    abstract class Box implements Built<Box, BoxBuilder> {
        int get width;
        int get height;
    }

异步代码

Kotlin

    fun heavyComputation() {
        async {
            ...
            val result = computation.await()
            ...
        }
    }

Dart

    void heavyComputation() async {
        ...
        var result = await computation();
        ...
    }

总结结语:
如果你熟悉kotlin,那么在学习dart的过程中更容易更亲切。


动动手指头,点个赞呗。

Flutter烂笔头