Dart VS Kotlin

dart 其實跟kotlin很像,而kotlin很早也被谷歌列爲第一開發語言,那爲何沒有選擇kotlin而使用了dart呢, 我也說不上來O(∩_∩)O~~。git

下面對比下dart vs kotlin:github

Hello world

Kotlin數組

println("Hello, world!")
複製代碼

Dart安全

print("Hello, world!");
複製代碼

變量&常量

Kotlinbash

var myVar = 1
myVar = 2
val myConstant = 5
複製代碼

Dartapp

var myVar = 1;
myVar = 2;
const myConstant = 5;
複製代碼

顯示類型

Kotlin異步

val explicitVar: Int = 7
複製代碼

Dartasync

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爛筆頭
相關文章
相關標籤/搜索