Kotlin学习-基本语法

根据学习情况,持续更新。

定义本地变量

在定义变量的时候可以不指定类型,Kotlin通过类型推导来决定。参见下面的b变量
只读变量

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

条件语句

和java一样

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

集合

Kotlin 的集合都在命名空间 kotlin.collections。

  • Lists
    List是只读集合,MutableList是可变集合。
    创建集合使用listOf()mutableListOf()
    例如:
    val items = listOf(1, 2, 3)
  • Arrays
  • Maps
    HashMap, LinkedHashMap, TreeMap
  • Sets
    setOf(),mutableSetOf()
    LinkedHashSet, HashSet, TreeSet
  • Sequences

三元运算

Kotlin中 不支持三目运算符,可以使用if..else来实现

//if表达式 三元表达式
fun method2():Int {
val a = 100
val b = 50
return if (a > b) a else b
}

package和import

源代码可以在开始的地方声明包

package foo.bar

fun baz() {}

class Goo {}

// ...

所有的内容都在包声明中,例如baz的完整名是foo.bar.baz
如果未声明包,那么所有内容都属于‘默认包’,没有名字

import语法,比较好理解,这个as挺有用的

import foo.Bar // Bar is now accessible without qualification
import foo.* // everything in 'foo' becomes accessible
// 有命名冲突的时候可以使用as关键字重命名
import foo.Bar // Bar is accessible
// bBar stands for 'bar.Bar'
import bar.Bar as bBar

extension functions and extension properties

  1. Extension Functions
    给MutableList增加swap功能
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}

val l = mutableListOf(1, 2, 3)
l.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'l'
  1. Extension Properties

Generics

使用类型参数做通用编程

class Box<T>(t: T) {
var value = t
}

// 通常需要在使用的时候指定参数类型
val box: Box<Int> = Box<Int>(1)
// 如果参数是可推导的话,可以省略。下面自动推导为Int类型
val box = Box(1)