kotlin 語言入門指南(一)--基礎語法


 

 

 

基於官網的Getting Start的基礎語法教程部分,一共三節,這篇是第一節,翻譯如下:

 

基礎語法

 

定義一個包

包的聲明必須放在文件頭部:

 

package my.demo

import java.util.*

// ...

 

不需要加上package的路徑,kotlin可以自動定位package的位置。

查看更多packages

 

 

定義函數

參數是兩個int型,並且返回值也是int型的函數:

fun sum(a: Int, b: Int): Int {
    return a + b
}

 

沒有指定返回值的函數表達式,編輯器會自動推斷返回類型:

fun sum(a: Int, b: Int) = a + b

 

無返回值的函數(Unit,相當於java的Void):

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

 

Unit聲明可以省略:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

 

查看Functions

 

 

定義變量

定義不可變變量:

val a: Int = 1  // 指定類型的變量
val b = 2   // 推斷為`Int`型
val c: Int  // 沒有初始值時必須指定變量類型
c = 3       // 賦值

 

定義可變變量:

var x = 5 // 推斷為`Int`型
x += 1

 

查看更多 Properties And Fields

 

注釋 

 同java與javascript,支持單行與塊注釋:

// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

不同於java的是,kotlin的區塊注釋是可以嵌套的。

查看更多Documenting Kotlin Code

 

 

字符串模板

var a = 1
// 字符變量:
val s1 = "a is $a" 

a = 2
// 任意表達式:
val s2 = "${s1.replace("is", "was")}, but now is $a"

查看更多String templates

 

 

If語句

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

 

if的表達式寫法:

fun maxOf(a: Int, b: Int) = if (a > b) a else b

查看更多 if-expressions

 

 

Null的用法

引用的參數可能為null時,應該標記為null

例:str 不能被轉換為 Int 型時會返回null: 

fun parseInt(str: String): Int? {
    // ...
}

 

函數中使用null:

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    // Using `x * y` yields error because they may hold nulls.
    if (x != null && y != null) {
        // x and y are automatically cast to non-nullable after null check
        println(x * y)
    }
    else {
        println("either '$arg1' or '$arg2' is not a number")
    }    
}

// ...
if (x == null) {
    println("Wrong number format in arg1: '${arg1}'")
    return
}
if (y == null) {
    println("Wrong number format in arg2: '${arg2}'")
    return
}

// x and y are automatically cast to non-nullable after null check
println(x * y)

 

查看更多 Null-safety

 

 

類型檢查與自動轉換

 

is 操作符來判斷對象是否屬於某一類型,如果不可變變量或者屬性是被檢查的類型的實例,就不需要再為變量指定類型,在作用域內可以直接當成被檢查的類型使用:

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // 在此作用域里`obj` 自動被當成 `String` 類型使用
        return obj.length
    }

    // `obj` 在外層仍然是 `Any` 類型
    return null
}

fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` 自動轉為 `string` 類型
    return obj.length
}

亦或

fun getStringLength(obj: Any): Int? {
    // `&&` 操作符右邊的 `obj` 自動轉為 `String` 類型
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}

查看更多Classes and Type casts

 

 

 

for循環

val items = listOf("apple", "banana", "kiwi")
for (item in items) {
    println(item)
}

or

val items = listOf("apple", "banana", "kiwi")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

 

查看更多 for loop

 

 

while

val items = listOf("apple", "banana", "kiwi")
var index = 0
while (index < items.size) {
    println("item at $index is ${items[index]}")
    index++
}

查看更多See while loop

 

 

 

when語句

fun describe(obj: Any): String =
when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
}

查看更多when expression

 

 

 

 Range

 判斷數字是否在范圍內:

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}

 

判斷數字是否超出范圍:

val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}
if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
}

 

范圍遍歷:

for (x in 1..5) {
    print(x)
}

 

過程遍歷:

for (x in 1..10 step 2) {
    print(x)
}
for (x in 9 downTo 0 step 3) { print(x) }

 

 查看更多Ranges

 

 

 

使用Collections

遍歷collections

for (item in items) {
    println(item)
}

 

使用 in 關鍵字判斷集合(collection)里是否包含某個對象(object):

when {
    "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") }

 

使用lambda表達式來過濾(filter)或映射(map)集合(collections):

fruits
.filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) }

 

 

 轉載請注明原文地址:http://www.cnblogs.com/joejs/p/6875128.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM