您的位置:首页 > 其它

Kotlin使用(一)基本语法

2017-06-23 16:38 330 查看

基本语法

定义包

package my.demo

import java.util.*
// ……


定义函数

函数声明:

带有两个 Int 参数、返回 Int 的函数:

函数参数使用 Pascal 表示法定义,即 name: type。参数用逗号隔开。每个参数必须有显式类型。

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


将表达式作为函数体、返回值类型自动推断的函数:

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


函数返回无意义的值:

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

//Unit 返回类型可以省略:
fun printSum(a: Int ,b: Int){
println("${a+b}")
}


默认参数

函数参数可以有默认值,当省略相应的参数时使用默认值。与其他语言相比,这可以减少重载数量。

fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size()) {
……
}


可变数量的参数(Varargs)

函数的参数(通常是最后一个)可以用 vararg 修饰符标记:

fun <T> asList(vararg ts: T): List<T> {
val result = ArrayList<T>()
for (t in ts) // ts is an Array
result.add(t)
return result
}


泛型函数

函数可以有泛型参数,通过在函数名前使用尖括号指定。

fun <T> singletonList(item: T): List<T> {
// ……
}


函数用法:

//以第一个函数为例
val sun = sum(2 + 3)


成员函数

成员函数是在类或对象内部定义的函数

class Sample() {
fun foo() { print("Foo") }
}


成员函数以点表示法调用

Sample().foo() // 创建类 Sample 实例并调用 foo


定义局部变量

一次赋值(只读)的局部变量 :

val a: Int = 1  // 立即赋值
val b = 2   // 自动推断出 `Int` 类型
val c: Int  // 如果没有初始值类型不能省略
c = 3       // 明确赋值


可变变量:

var x = 5 // 自动推断出 `Int` 类型
x += 1


要使用一个属性,只要用名称引用它即可,就像 Java 中的字段:

fun copyAddress(address: Address): Address {
val result = Address() // Kotlin 中没有“new”关键字
result.name = address.name // 将调用访问器
result.street = address.street
// ……
return result
}


Getters 和 Setters

声明一个属性的完整语法是

var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>]


其初始器(initializer)、getter 和 setter 都是可选的。属性类型如果可以从初始器 (或者从其 getter 返回值,如下文所示)中推断出来,也可以省略。

例如:

var allByDefault: Int? // 错误:需要显式初始化器,隐含默认 getter 和 setter
var initialized = 1 // 类型 Int、默认 getter 和 setter


一个只读属性的语法和一个可变的属性的语法有两方面的不同:1、只读属性的用 val开始代替var 2、只读属性不允许 setter

val simple: Int? // 类型 Int、默认 getter、必须在构造函数中初始化
val inferredType = 1 // 类型 Int 、默认 getter


一个自定义的 setter 的例子:

var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value) // 解析字符串并赋值给其他属性
}


自 Kotlin 1.1 起,如果可以从 getter 推断出属性类型,则可以省略它:

val isEmpty get() = this.size == 0  // 具有类型 Boolean


幕后字段

Kotlin 中类不能有字段。然而,当使用自定义访问器时,有时有一个幕后字段(backing field)有时是必要的。为此 Kotlin 提供一个自动幕后字段,它可通过使用 field 标识符访问。

var counter = 0 // 此初始器值直接写入到幕后字段
set(value) {
if (value >= 0)
field = value
}


field 标识符只能用在属性的访问器内。

如果属性至少一个访问器使用默认实现,或者自定义访问器通过 field 引用幕后字段,将会为该属性生成一个幕后字段。

幕后属性

如果你的需求不符合这套“隐式的幕后字段”方案,那么总可以使用 幕后属性(backing property):

private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
get() {
if (_table == null) {
_table = HashMap() // 类型参数已推断出
}
return _table ?: throw AssertionError("Set to null by another thread")
}


从各方面看,这正是与 Java 相同的方式。因为通过默认 getter 和 setter 访问私有属性会被优化,所以不会引入函数调用开销。

编译期常量

已知值的属性可以使用 const 修饰符标记为 编译期常量。 这些属性需要满足以下要求:

–位于顶层或者是 object 的一个成员

–用 String 或原生类型 值初始化

–没有自定义 getter

这些属性可以用在注解中:

const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"

@Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { …… }


使用条件表达式

If表达式

在 Kotlin 中,if是一个表达式,即它会返回一个值。 因此就不需要三元运算符(条件 ? 然后 : 否则),因为普通的 if 就能胜任这个角色。

// 传统用法
var max = a
if (a < b) max = b

// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}

// 作为表达式
val max = if (a > b) a else b


if的分支可以是代码块,最后的表达式作为该块的值:

val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}


如果你使用 if 作为表达式而不是语句(例如:返回它的值或者把它赋给变量),该表达式需要有 else 分支。

When 表达式

when 取代了类 C 语言的 switch 操作符。其最简单的形式如下:

when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // 注意这个块
print("x is neither 1 nor 2")
}
}


when 将它的参数和所有的分支条件顺序比较,直到某个分支满足条件。 when 既可以被当做表达式使用也可以被当做语句使用。如果它被当做表达式, 符合条件的分支的值就是整个表达式的值,如果当做语句使用, 则忽略个别分支的值。(像 if 一样,每一个分支可以是一个代码块,它的值是块中最后的表达式的值。)

如果其他分支都不满足条件将会求值 else 分支。 如果 when 作为一个表达式使用,则必须有 else 分支, 除非编译器能够检测出所有的可能情况都已经覆盖了。

如果很多分支需要用相同的方式处理,则可以把多个分支条件放在一起,用逗号分隔:

when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}


我们可以用任意表达式(而不只是常量)作为分支条件

when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}


我们也可以检测一个值在(in)或者不在(!in)一个区间或者集合中:

when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}


另一种可能性是检测一个值是(is)或者不是(!is)一个特定类型的值。注意: 由于智能转换,你可以访问该类型的方法和属性而无需任何额外的检测。

fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}


when 也可以用来取代 if-else if链。 如果不提供参数,所有的分支条件都是简单的布尔表达式,而当一个分支的条件为真时则执行该分支:

when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}


For 循环

for 循环可以对任何提供迭代器(iterator)的对象进行遍历,语法如下:

for (item in collection) print(item)


循环体可以是一个代码块。

for (item: Int in ints) {
// ……
}


如上所述,for 可以循环遍历任何提供了迭代器的对象。即:

有一个成员函数或者扩展函数 iterator(),它的返回类型

有一个成员函数或者扩展函数 next(),并且

有一个成员函数或者扩展函数 hasNext() 返回 Boolean。

这三个函数都需要标记为 operator。

对数组的 for 循环会被编译为并不创建迭代器的基于索引的循环。

如果你想要通过索引遍历一个数组或者一个 list,你可以这么做:

for (i in array.indices) {
print(array[i])
}


注意这种“在区间上遍历”会编译成优化的实现而不会创建额外对象。

或者你可以用库函数 withIndex:

for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}


While 循环

while 和 do..while 照常使用

while (x > 0) {
x--
}

do {
val y = retrieveData()
} while (y != null) // y 在此处可见


使用 when 表达式

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


使用区间(range)

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


使用集合

对集合进行迭代:

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


使用 in 运算符来判断集合内是否包含某实例:

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


使用 lambda 表达式来过滤(filter)和映射(map)集合:

fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: