Kotlin基础语法

原文地址

Defining packages

包的声明应该在源文件的顶端

<code>package my.demo  
import java.util.  * // ...

目录和包不要求匹配

Defining functions

函数有两个整形参数和返回整形结果

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

函数根据表达式内容推出返回结果
<pre><code>fun sum(a: Int, b: Int) = a + b</pre></code>
函数无返回值

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}")
}

Defining local variables

定义常量

val a: Int = 1  // immediate assignment 
val b = 2   // `Int` type is inferred
val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment

可变变量

var x = 5 // `Int` type is inferred
x += 1

Comments

就像Java和JavaScript,Kotlin 支持行尾和块注释

// This is an end-of-line comment 
/* This is a block comment on multiple lines. */

和Java不同的是,Kotlin块注释能够被嵌套

Using string templates

var a = 1
// simple name in template:
val s1 = "a is $a" 

a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
Using conditional expressions
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

Using if as an expression:

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

Using nullable values and checking for null

引用的值如果可能为空的话那么必须被明确的标注为可空的。
返回空如果str不可被转化为整数

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

用一个函数返回可空的值

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)

Using type checks and automatic casts

is操作符检查表达式是否是某个类型的实例。如果一个局部变量需要被检查是某个特定的类型,那么就没必要显示的强转

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

或者

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

    // `obj` is automatically cast to `String` in this branch
    return obj.length
}

甚至

fun getStringLength(obj: Any): Int? {
    // `obj` is automatically cast to `String` on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}

Using a for loop

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

或者

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

Using a while loop

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

Using when expression

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

Using ranges

检查数字在某个范围内用in操作符

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)
}

Using collections

遍历一个集合

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

检查集合是否包含某个对象用in操作符

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

使用lambda表达式去过滤和转换集合

fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Kotlin简介 Kotlin是一门与Swift类似的静态类型JVM语言,由JetBrains设计开发并开源。与J...
    吸给007阅读 3,255评论 1 1
  • 1.函数 (1)Main函数默认是Unit返回类型,可以定义其他返回类型:Int (2)直接声明一个函数,给出返回...
    贾里阅读 3,462评论 0 0
  • 写在前面 虽然在没有系统学过Java的情况下来直接学Kotlin可能不是特别好,但毕竟之前学过C/C++/C#,对...
    士拔鼠阅读 1,540评论 0 0
  • 一、常量与变量(val,var) 1.什么是常量? 1 .val = value ,值类型;2.类似Java的fi...
    Serenity那年阅读 3,520评论 0 7
  • 每种编程语言都有一定的语法、语义和执行顺序(同步),学习一种新语言也都是从这三者出发,下面我们就只针对kotlin...
    samychen阅读 9,993评论 0 6