kotlin基础语法

1. 包定义 package

package my.demo

2. 方法定义 fun

fun sum(a: Int, b: Int): Int {//定义方法的关键字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 { //返回一个没有意义的值,也就是没有返回值的情况,使用Unit

    println("sum of $a and $b is ${a + b}") //$a是变量a的引用写法,${}是字符串模板的写法
}

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

3. 变量定义

val a: Int = 1 //直接赋值,变量名a,类型Int

val b = 2 // 直接赋值,自动推断为`Int` 类型

val c: Int // 初始化时没有赋值,必须指定类型

c = 3 // deferred assignment

4.注释

//表示当行注释

/*多行注释*/ 

5.字符串模板

var a = 1

val s1 = "a is $a" //模板里单一变量引用,使用$符号

a = 2 

val s2 = "${ s1.replace("is", "was") }, but now is $a" // 模板里任意表达式,使用${};输出结果为a was 1, but now is 2

6.条件表达式

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

  fun maxOf(a: Int, b: Int) = if (a > b) a else b //方法体是一个表达式,返回值类型自动推断 

7. null空值检查,如果一个值有可能为空,就要显示地使用?标记

fun parseInt(str: String): Int? { //返回值有可能为空,使用问号?标记;表示如果str不包含整数返回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") }

}

 8. 类型检查和自动转换

使用 is 操作符判断一个对象是不是某个类型的实例

fun getStringLength(obj: Any): Int? {

if (obj is String) { //使用 is 判断 obj是不是String类型

// 自动转换为String类型

return obj.length

return null // 语句结尾可以不使用分号结束

或者

fun getStringLength(obj: Any): Int? {

if (obj !is String){//如果obj不是String类型

return null

// `obj` is automatically cast to `String` in this branch

return obj.length

或者

fun getStringLength(obj: Any): Int? {

// && 右边的obj自动转换为String类型

if (obj is String && obj.length > 0) {

return obj.length

}

return null

}

9. 使用for循环

val items = listOf("apple", "banana", "kiwi")

for (item in items) { //形式 for(each in list){}

println(item)

或者

val items = listOf("apple", "banana", "kiwi")

for (index in items.indices) {//items.indices是list的索引列表

println("item at $index is ${items[index]}") //${}字符串模板

}

10. 使用while循环

val items = listOf("apple", "banana", "kiwi")

var index = 0

while (index < items.size) {

println("item at $index is ${items[index]}")

index++

}

11. 使用when表达式(替代switch语句)

fun describe(obj: Any): String =

when (obj) {

1 -> "One"

"Hello" -> "Greeting"

is Long -> "Long"

!is String -> "Not a string"

else -> "Unknown"

//调用describe这个方法,就会根据参数的不同返回String类型的不同值

12. 使用范围 in 关键字

使用 in 判断一个数是否在某个范围内

val x = 10

val y = 9

if (x in 1..y+1) { //范围形式(小端..大端);x是否在1到10(y+1)之间;结果是在的

println("fits in range")

检查一个数是否在超出范围:

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

if (-1 !in 0..list.lastIndex) { //-1是否 不在 0到list的长度;结果是不在的

println("-1 is out of range")

}

if (list.size !in list.indices) { //list.size 是否 不在 list索引内;结果是不在的

println("list size is out of valid list indices range too")

迭代一个范围:

for (x in 1..5) {

print(x)

} //输出结果为:12345

迭代一个范围,添加步长

for (x in 1..10 step 2) {//步长为2

print(x)

}//输出:13579

for (x in 9 downTo 0 step 3) {

print(x)

}//输出9630

13. 使用集合

迭代一个集合:

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") } //过滤出以a开头的

.sortedBy { it } //排序

.map { it.toUpperCase() } //转为大写

.forEach { println(it) } //遍历输出,注意:it是集合本身自带的默认的变量名称

使用filter过滤一个list的item为正数

val positives = list.filter { x -> x > 0 }

或者val positives = list.filter { it > 0 }
 

 

posted @ 2017-05-20 12:35  yongfengnice  阅读(689)  评论(0编辑  收藏  举报