Kotlin 基础语法详细介绍

网友投稿 238 2023-05-14


Kotlin 基础语法详细介绍

Kotlin 基础语法详细介绍

基础语法

定义包名

包名的定义应当在源文件的头部

package my.demo

import java.util.*

// ...

文件路径和包名并不要求匹配,源文件可以被放置在文件系统任意位置

参考:包

定义函数

函数有两个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 {

print(a + b)

}

Unit类型的返回值类型可以省略:

fun printSum(a: Int, b: Int) {

print(a + b)

}

参见:函数

定义局部变量

定义只读类型的局部变量:

val a: Int = 1

val b = 1 // `Int` 类型是被编译器推理出

val c: Int // 当变量的初始值没有被提供时,需要定义变量的类型

c = 1 // 赋值

可变局部变量

var x = 5 // `Int` 类型是被编译器推理出的

x += 1

可参见:属性与变量

注释

就像Java与JavaScripe,Kotlin也支持行注释与代码块注释。

// 这是一段行注释

/* 这是一段代码块

注释 */

不像Java,代码块注释在Kotlin中是可以被叠加的。

参见:Kotlin代码文档

使用字符串模板

fun main(args: Array) {

if (args.size == 0) return

print("First argument: ${args[0]}")

}

参见:字符串模板

使用条件表达式

fun max(a: Int, b: Int): Int {

if (a > b)

return a

else

return b

}

使用 if 作为一个表达式返回值:

fun max(a: Int, b: Int) = if (a > b) a else b

参见:if 表达式

使用可空变量并检测是否为空

一个引用必须明确的被设置为可为空当其可能为空值时。

返回值为null 如果str 没有包含数值:

fun parseInt(str: String): Int? {

// ...

}

函数的返回值可能为空:

fun main(args: Array) {

if (args.size < 2) {

print("Two integers expected")

return

}

val x = parseInt(args[0])

val y = parseInt(args[1])

// Using `x * y` yields error because they maIvrcDBy hold nulls.

if (x != null && y != null) {

// x and y are automatically cast to non-nullable after null check

print(x * y)

}

}

或者:

// ...

if (x == null) {

print("Wrong number format in '${args[0]}'")

return

}

if (y == null) {

print("Wrong number format in '${args[1]}'")

return

}

// x and y are automatically cast to non-nullable after null check

print(x * y)

参见:空安全

使用类型检测和类型自动转换

is 操作符用于检测一个表达式是否是某一种类型,假如可变参数或者属性被检测为某一种类型,那么就不在需要明确的类型转换:

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

}

或者:

fun getStringLength(obj: Any): IntIvrcDB63; {

if (obj !is String)

return null

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

return obj.length

}

或者:

fun getStringLength(obj: Any): Int? {

// `obj` is automatically cast to `String` on the right-hand side of `&&`

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

return obj.length

return null

}

参见:类和类型转换

使用for循环

fun main(args: Array) {

for (arg in args)

print(arg)

}

或者:

for (i in args.indices)

print(args[i])

参见:for循环

使用while循环

fun main(args: Array) {

var i = 0

while (i < args.size)

print(args[i++])

}

参见:while循环

使用when表达式

fun cases(obj: Any) {

when (obj) {

1 -> print("One")

"Hello" -> print("Greeting")

is Long -> print("Long")

!is String -> print("Not a string")

else -> print("Unknown")

}

}

参见:when表达式

使用范围表达式

检测一个数值是否在一个范围内,若在则使用in操作符

if (x in 1..y-1)

print("OK")

检测一个数值是否不在一个范围内,若不在:

if (x !in 0..array.lastIndex)

print("Out")

迭代一个数据范围项:

for (x in 1..5)

print(x)

参见:范围

使用集合

迭代一个集合:

for (name in names)

println(name)

检测一个集合是否包含某个数据项,使用in操作符

if (text in names) // names.contains(text) is called

print("Yes")

使用lambda表达式过滤或者转换一个集合:

names

.filter { it.startsWith("A") }

.sortedBy { it }

.map { it.toUpperCase() }

.forEach { print(it) }

参见:高阶函数和Lambda表达式

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Mybaits配置文件之动态SQL配置备忘录
下一篇:抽象类可以实现接口吗(抽象类可以扩展接口吗)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~