Bootstrap

Kotlin语法--基础入门

点此进入Kotlin在线编程练习

点此阅读Kotlin官方文档

点此阅读官方教程

什么是Kotlin?

一种Android官方推荐的开发语言,可与Java兼容,适用于多平台开发。

用Kotlin输出"Hello world!"

fun main() {
    println("Hello world!")
}
//这是单行注释
/* 这是
多行注释*/

Kotlin 应用程序的入口点是main函数。

函数也可以接受参数:

fun main(args: Array<String>) {
   println(args.contentToString())
}

可以同时使用println(),readln(),print()来打印请求和显示用户输入的消息:

// Prints a message to request input
println("Enter any word: ")

// Reads and stores the user input. For example: Happiness
val yourWord = readln()

// Prints a message with the input
print("You entered the word: ")
print(yourWord)
// You entered the word: Happiness

//println打印参数并添加换行符
//print将参数打印到标准输出
//readln()读取用户输入的整行作为字符串

变量

声明变量使用var或val(二者区别在于:val初始化后无法改变值,var可重新赋值)

var x: Int = 5
x += 1 //Kotlin中用换行来分隔语句
val x: Int = 5 //变量的类型声明写在冒号之后
val x = 5 //初始化时也可以不写类型
val y: Int
y =3 //先声明再初始化,就需要事先指定数据类型

可以在顶层声明变量

val PI = 3.14
var x = 0

fun incrementX() {
    x += 1
}
// x = 0; PI = 3.14
// incrementX()
// x = 1; PI = 3.14

变量类型

  • String: 文本
  • Int: 整数
  • Double:小数
  • Float: 小数
  • Boolean: 布尔

文档中更详细的分类
关于字符串模版

函数

如何用函数实现两个整数的相加?

fun sum(a: Int, b: Int): Int{
    return a+b
}
//使用fun关键字定义函数,fun后是函数名,小括号内是形式参数,参数用逗号分隔
//第三个Int是对函数返回类型的推断
//不返回任何有意义的值:使用Unit;也可以直接省略这个部分
fun printSum(a: Int, b: Int): Unit{
    println("sum of $a and $b is ${a+b}")
}

再看一个例子:

fun birthdayGreeting(name: String, age: Int): String {
    val nameGreeting = "Happy Birthday, $name!"
    val ageGreeting = "You are now $age years old!"
    return "$nameGreeting\n$ageGreeting"
}
fun main() {
    println(birthdayGreeting("Rover", 5)) //调用函数,为形式参数传值
    println(birthdayGreeting("Rex", 2))
}
//Happy Birthday, Rover!
//You are now 5 years old!
//Happy Birthday, Rex!
//You are now 2 years old!
//

也可传递具名实参,这样就不受传参顺序的影响:

println(birthdayGreeting(name = "Rex", age = 2))
println(birthdayGreeting(age = 2, name = "Rex"))

还可以指定默认实参:

fun birthdayGreeting(name: String = "Rover", age: Int): String {
    return "Happy Birthday, $name! You are now $age years old!"
}

定义一个矩形类

class Rectangle(val height: Double, val length: Double) {
    val perimeter = (height + length) * 2 
}
fun main() {
    val rectangle = Rectangle(5.0, 2.0)
    println("The perimeter is ${rectangle.perimeter}")
}
//类的属性可以在其声明或正文中列出
//类声明中列出的参数的默认构造函数将自动可用

类之间的继承由冒号声明,想使类可继承,要将其标记为open

open class Shape //open--可继承

class Rectangle(val height: Double, val length: Double): Shape() {
    val perimeter = (height + length) * 2
}
\\shape类被继承

关于类的更多内容
关于对象和实例

条件表达式与循环

if else

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

for loop

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}
//或者这么写
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {//indices返回下标索引
    println("item at $index is ${items[index]}")
}
//item at 0 is apple
//item at 1 is banana
//item at 2 is kiwifruit

when loop

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

when expression

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

Ranges

检查是否在范围内
可规定步长

val x = 10
val y = 9
if (x in 1..y+1) {//..是封闭范围
    println("fits in range")
}
//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")
}
//-1 is out of range
//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) {
    print(x)
}
println()
for (x in 9 downTo 0 step 3) {
    print(x)
}
//13579
//9630

set

遍历集合,可使用in,也可以用in检查是否在范围内

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

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

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
    .filter { it.startsWith("a") }
    .sortedBy { it }
    .map { it.uppercase() }
    .forEach { println(it) }
//APPLE
AVOCADO

null

当值可能时,必须将引用显式标记为可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("'$arg1' or '$arg2' is not a number")
    }
}
//42
//'a' or '7' is not a number
//'a' or 'b' is not a number

可为 null 的类型和不可为 null 的类型

;