一、kotlin基本语法


1.定义变量、常量

复杂写法
1
var a : Int = 1
根据赋值就知其类型
1
var a = 1

2. 常量

1
val a = 1

3. 字符串拼接

  • java
1
2
3
4
5
String a = "You are an ";

String b = "ABC";

String result = a + b;
  • kotlin
1
2
3
4
5
var a = "You are an "

var b = "ABC"

String result = "$a$b"

4. 定义函数

  • 无参无返回值
1
fun myFun(){}
  • 无参有返回值
1
2
3
fun myFun() : String{
return ""
}
  • 有参有返回值
1
2
3
fun myFun(myParam : String) : String{
return ""
}

5.注释

单行注释//

kotlin块注释支持嵌套,Java不支持嵌套

1
2
3
4
5
6
/* 
这是一个多行的
块注释。
/*再嵌套一个
块注释 */
*/

6.if else 表达式

if else可以返回值

1
2
3
4
5
var result = if(3 > 4){
"wrong"
}else{
"right"
}

7. when语句

kotlin没有java中的swith case语句

1
2
3
4
5
6
7
8
fun testWhen(result : Int){
when(result){
0 -> {}
1 -> {}
2 -> {}
else -> {}
}
}

多个分支使用相同的处理方式:

1
2
3
4
5
6
7
fun testWhen(result : Int){
when(result){
0 -> {}
1,2 -> {}
else ->{}
}
}

when语句还能像kotlin的if语句那样作为表达式:

1
2
3
4
5
6
7
fun testWhen(result : Int) : String{
return when(result){
0 -> "is 0"
1,2 -> "is 1 or 2"
else -> "is nothing"
}
}

8. is关键字与Any类型

kotlin中可以用is关键字判断对象的类型,有点像java的 instanceof
Any是Kotlin中所有类都有一个共同的父类,有点像Java中的Object,但这个类只有equals()、 hashCode()、toString()方法。

1
2
3
4
5
6
7
8
fun testIs(bean : Any) : String {

when (bean) {
is String -> return "type is String"
is Int -> return "type is int"
else -> return "Nothing"
}
}

9. for循环

1
2
3
4
var list = ArrayList<String>()
list.add("gz")
list.add("sz")
list.add("dg")

写法一: 只要值,不要索引:

1
2
3
for(city in list) {
Log.e(TAG, "--gnt-result: " + city)
}

写法二: 值和索引,但用到api:

1
2
3
4
for (index in list.indices) {
Log.e(TAG, "--gnt-city: " + list[index])
Log.e(TAG, "--gnt-1-city: " + list.get(index))
}

写法三: 值和索引都能获取到:

1
2
3
4
for ((index, value) in list.withIndex()) {
Log.e(TAG, "key: $index, value: $value")
Log.e(TAG, "-gnt-key: " + index + ", value: " + value)
}

10. 集合

kotlin也有跟java一样的List, Map, Set集合,但是他们都是只读的,不可add, remove等修改操作。
要可修改得要用: MutableList,MutableSet,MutableMap
只读集合的初始化

1
2
3
var list = listOf<Int>()
var set = setOf<String>()
var map = mapOf<String, String>()

可修改集合的初始化

1
2
3
var mutableList = mutableListOf<Int>()
var mutableSet = mutableSetOf<String>()
var mutableMap = mutableMapOf<String, String>()