与java的不同
- 不区分原生类型和包装类型
- 变量和函数可独立存在,无需定义在类的里面
- 不强制
; - 新建对象无需使用
new关键字 - 一个kt文件可以定义多个public class
基本类型
与java的类型对比
| Kotlin | Java |
|---|
| Byte | Byte |
| Int | Integer |
| Long | Long |
| Float | Float |
| Double | Double |
| Char | Character |
| String | String |
| Array | Object[] |
变量定义
函数定义
1 2 3 4 5 6 7 8 9
| fun add(a: Int, b: Int): Int { return a + b }
val add = { a: Int, b: Int -> a + b }
val c = add(1, 2)
|
循环
1 2 3 4
| val list = listOf(1, 2, 3) for (item in list) { println(item) }
|
对象
类定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Apple
class Apple ( val name: String )
@Ann class Apple ( @Ann val name: String )
val apple = Apple()
|
类的静态变量定义
我们也可以直接把变量定义在类外面
1 2 3 4 5 6 7
| class Foo{ companion object { const val BAR = 1 } }
println(Foo.BAR)
|
接口定义
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface Fruit { val name: String fun foo() }
class Apple( override val name: String = "Apple" ) : Fruit { override fun foo() { TODO("Not yet implemented") } }
|
数据类定义
自动生成equals、hashCode,toString,copy等方法
1 2 3
| data class Foo ( val bar: Int )
|
注解定义
1 2 3 4 5
| @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.FIELD, AnnotationTarget.CLASS) annotation class Ann {
}
|
常用数据结构
List
1 2 3 4
| val list = listOf(1, 2, 3)
val arrayList = arrayListOf(1, 2, 3)
|
Map
1 2 3 4 5 6 7 8 9
| val map = mapOf(1 to 2, 3 to 4)
val hashMap = hashMapOf(1 to 2, 3 to 4) val linkHashMap = linkedMapOf(1 to 2, 3 to 4)
val v = map[1] val v = map[0]
|
Set
1 2 3 4
| val set = setOf(1, 2, 3)
val hashSet = hashSetOf(1, 2, 3)
|