1.定义函数
/**
* 带有两个 Int 参数、返回 Int 的函数
*/
fun sum(a: Int, b: Int): Int {
return a + b
}
a:Int 其中a表示传入参数,Int表示参数类型,括号外:Int表示返回值类型
/**
* 将表达式作为函数体 返回值类型自动推断的函数
*/
fun sum1(a: Int, b: Int) = a + b
/**
*函数返回无意义的值
*/
fun printSum(a: Int, b: Int, c: Int): Unit {
println("sum of $a and $b and $c is ${a + b + c}")
}
没有返回值时,用:Unit表示默认可以不写,$符号表示转义
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
2.赋值语句,val相当于final只能赋值一次,var可以多次赋值
fun test2() {
val a: Int = 1//立即赋值
val b = 2 //自动推断出其数据类型
val c: Int//如果没有初始值数据类型不能忽略
c = 3 //明确赋值
//可变变量
var x = 5//自动推断出Int类型
x += 1
}
3.使用字符串模板
fun test3() {
var a = 3
val str1 = "a is $a"
a = 6
val str2 = "${str1.replace("is", "am")} but now is $a"
println(str2)
}
4.使用条件表达式
private fun test4() {
val max = getMax(3, 3)
println(max)
println(maxof(100, 100))
}
fun maxof(a: Int, b: Int) = if (a > b) a else b
fun getMax(a: Int, b: Int): Int {
if (a > b) {
return a
} else if (a < b) {
return b
} else {
return a
}
}
5.使用可空值及null的检测(返回值后面加?)
fun getStringLength(obj: Any): Int? {
if (obj is String) {
return obj.length
}
return null
}
6.使用类型检测及自动类型转换(通过is)
fun getStringLength(obj: Any): Int? {
if (obj is String) {
return obj.length
}
return null
}
fun getStringLength1(obj: Any): Int? {
if (obj !is String) {
return null
}
return obj.length
}
fun getStringLength2(obj: Any): Int? {
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}
7.for循环
private fun test7() {
val items = listOf("1", "2", "3", "4", "5", "5897")
for (item in items) {
println(item)
}
}
- while循环
private fun test8() {
var items = listOf<String>("wade", "kobe", "james", "paul", "Irving", "rose", "jordan")
var index = 0
while (index < items.size) {
println("$index is ${items[index]}")
index++
}
}
9.使用when表达式
private fun describe(obj: Any?) {
when (obj) {
is Int -> println("obj is int")
is String -> println("obj is String")
is Long -> println("obj is Long")
else -> println("unknow")
}
}
10.使用区间, 使用 in 运算符来检测某个数字是否在指定区间内
private fun testRange(a: Int) {
val list = listOf<String>("a", "b", "c")
println(list.lastIndex)
if (0 in 0..list.lastIndex) {
println("0 is in Range")
} else {
println("0 is Out of Range")
}
if (list.size - 1 !in list.indices) {
println("list size is out of valid list indices range too")
}
//step后面的数字表示每隔 该数字-1打印一次
for (x in 1..10 step 5) {
println(x)
}
// 9 down to 0 表示从9到0
for(x in 9 downTo 0 step 2){
println(x)
}
}
11.使用集合 进行迭代
private fun test10() {
val items = listOf<String>("wa","orange","noy","hui","cdf")
for(item in items){
println(item)
}
when{
"orange" in items -> println("juicy")
"apple" in items -> println("apple")
else -> println("unKnow")
}
//使用lambda表达式来过滤与yin'she
val fruits = listOf<String>("apple","banana","orange","pear","melon")
fruits
.filter { it.startsWith("b") }
.sortedBy { it }
.map { it.toLowerCase() }
.forEach { println(it) }
}
网友评论