Kotlin官方文档

基础语法

基础语法概述

package与import

package com.ai
import kotlin.text.*
//与JAVA基本一样,只是不需要;结尾

程序入口函数

fun main() {
  println("hello world.")
}

fun main(args: Array<String>) {
  println(args.contentToString())
}
//带参和不带参两种入口函数形式,可与JAVA类比;

函数形式和参数形式后面具体介绍function

标准输入&输出

print("hello world")
println("hello world")

//readln()
println("please enter any words:")
val words = readln()
print("You enter words:")
print(words)

函数(Functions)

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

//函数体可以是一个表达式,其返回值会被自动推断
fun sum(a: Int, b: Int) = a + b

//函数返回值无实际意义时用Unit表示,也可以省略Unit返回值类型
fun sum(a: Int, b: Int): Unit {
  println("sum of $a and $b is &(a + b)")
}

fun sum(a: Int, b: Int) {
  println("sum of $a and $b is $(a + b)")
}

变量(Variables)

  • val:常量,被该关键字定义的变量其值在被初始化后就不可变,是只读的局部变量,不能被二次赋值
  • var:变量,被该关键字定义的变量其值是可变的
val x: Int = 5
// x = 7 //非法

var a: Int = 1
a = 2 //合法

//kotlin支持类型推断,可以自动识别所声明常量&变量的数据类型。
//声明常量&变量并且直接赋值时,可省略常量&变量名后的数据类型,kotlin会自动推断常量&变量的类型
val y = 5
var b = 3

//常量&变量只有被初始化后才是可用的。
//可以在声明常量&变量的同时就初始化,
//也可以先常量&变量后初始化,如果常量&变量的时候没有初始化,就必须要指定常量&变量的类型
val z: Int
z = 5

var c: Int
c = 5
c += 1

类与实例(classes & instances)

  • class关键字来定义一个类
  • 类的属性可以在其声明中或者函数体中
  • 只要在类声明里列出了带参数的默认构造函数,这个构造函数就会自动变为可用状态。
  • 类之间的继承关系通过冒号(:)声明。类默认是 final 修饰的(不可继承);若要让一个类可被继承,需将其标记为 open
open class Shape

class Rectangl(val height: Double, val width: Double): Shape() {
  val perimeter = (height + width) * 2
}

fun main() {
 val rectangle = Rectangle(5.0, 2.0)
 println("The perimeter of rectangle is $rectangle.perimeter")
}

注释

  • kotlin支持单行注释和多行注释(注释块)
  • 多行注释是可以嵌套的
//this is a single-line comment

/*
this is a multi-line comment
*/

/*
 this is a multi-line comment with sub-block
 /* this is a sun-block */
*/

字符串模板

  • 字符串模板中支持简单变量,也支持任意表达式
var a = 1
val s1 = "a is $a"

a = 2
val s2 = "${s1.replace("is", "was")}, but now is $a"
//a was 1, bu now is 2

条件表达式

  • 通常的写法:
fun maxOf(a: Int, b: Int): Int {
  if (a > b) {
    return a
  } else {
    return b
  }
}
  • kotlin中也可以用if表达式:
fun maxOf(a: Int, b: Int) = if (a > b) a else b

for循环

  • kotlin中的for循环只有迭代器形式的写法,需要用到in关键字
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
  println(item)
}

或者

val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
  println("item at $index is ${items[index]}")
}

while循环

val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
  println("item at $index is ${items[index]}")
  index++
}

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("x is $x, range is [1, ${y+1}], fits in range")
}
  • 检查数字不在一个范围内,需要用!in
val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
  println("-1 is outof 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)
}
  • 也可以在等差数列(progressions) 上遍历
for (x in 1..10 step 2) {
  print(x)
}
//13579
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
//9630

集合

  • 在集合上遍历
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
  println(item)
}
  • 检查一个集合中是否包含某个对象需要用关键字in
val items = listOf("apple", "banana", "kiwifruit")
when {
  "orange" in items -> println("juicy")
  "apple" in items  -> println("apple is fine too")
}
  • 借助 lambda 表达式来筛选(filter)和转换(map)集合里的元素
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter {it.startsWith("a")}
    .sortedBy {it}
    .map {it.uppercase()}
    .forEach {println(it)}

Kotlin 支持集合链式操作,每个方法返回新集合,继续调用下一个方法,逻辑清晰:

  1. filter { it.startsWith("a") }

    • filter:过滤方法,作用是保留集合中符合条件的元素,参数是一个 lambda 表达式({} 里的逻辑);
    • it:lambda 中默认的单个元素变量名(这里代表列表里的每个水果字符串);
    • startsWith("a"):字符串方法,判断是否以字母 a 开头;
    • 执行结果:筛选出 ["avocado", "apple"](banana/kiwifruit 不以 a 开头,被过滤掉)。
  2. sortedBy { it }

    • sortedBy:排序方法,按指定规则升序排列;
    • { it }:表示 “按元素自身的字符串默认排序规则(字母顺序)排序”;
    • 执行结果:["apple", "avocado"](apple 字母顺序在 avocado 前面)。
  3. map { it.uppercase() }

    • map:映射 / 转换方法,将集合中每个元素转换成新值
    • uppercase():字符串方法,将小写转成大写(注意:老版本 Kotlin 是 toUpperCase(),1.5+ 推荐 uppercase());
    • 执行结果:["APPLE", "AVOCADO"]
  4. forEach { println(it) }

    • forEach:遍历方法,对集合中每个元素执行指定操作(无返回值);
    • println(it):打印每个元素;
    • 执行结果:控制台依次输出:

可空值与控制检查

  • 可空值:Nullable values,允许被赋值为 null 的变量 / 值(Kotlin 中默认变量不可空,加 ? 才变为可空)
  • 空值检查:null checks,代码中判断变量是否为 null 的逻辑(如 if (x != null)),是 Kotlin 避免空指针的核心手段
//定义可空值
val name: String? = null

//函数返回值可空
fun parseInt(str: String): Int?{
 if (str == null || str != null && str.length == 0) return null
 //......
}

类型检查与自动转换

  • is关键字用来检查一个表达式是否为一个类型的实例
  • is 是 Kotlin 的类型检查运算符,对 val 声明的不可变变量做类型检查后,编译器会自动智能类型转换,无需手动写 as
  • is 替代了 Java 的 instanceof,且 Kotlin 的「智能类型转换」是核心特性(仅对不可变变量生效);
fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐