fun main(): Unit {
sayHello("Kotlin")
Person().sayHello("Kotlin")
Person.sayHello2("Kotlin")
PersonUtils.sayHello("Kotlin")
sayHelloSingle("Kotlin")
println(append('a', 'b', 'c'))
println("magic():${magic()}")
test5()
test6()
}
fun sayHello(name: String): String {
println("Hello $name!")
return name
}
class Person {
//成員方法
fun sayHello(name: String) {
println("Hello $name From Person")
}
//伴隨對象中的方法可以直接調(diào)用
companion object {
fun sayHello2(name: String) {
println("Hello $name From Person companion object")
}
}
}
//類似于Java中的靜態(tài)方法
object PersonUtils {
fun sayHello(name: String) {
println("Hello $name! from PersonUtils")
}
}
/**
*單表達式方法桃纯,當(dāng)方法僅有單個表達式時,可以省略花括號态坦,并在 = 后指定方法體即可
*/
fun sayHelloSingle(name: String) = println("Hello $name From 單表達式")
/**
*默認值,方法參數(shù)可以有默認值伞梯,當(dāng)省略相應(yīng)參數(shù)時使用默認值。與Java相比琐旁,可以減少重載數(shù)量
*/
fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {
}
/**
* 可變數(shù)量參數(shù)
*/
fun append(vararg str: Char): String {
val result = StringBuffer();
str.forEach {
result.append(it)
}
return result.toString()
}
/**
*局部方法 閉包涮阔?
*/
fun magic(): Int {
fun foo(x: Int): Int {
return x * x
}
var m = (1..100).random();
return foo(m)
}
/**
* 無參數(shù)方法改寫為lambda表達式
*/
fun test() {
println("無參數(shù)方法")
}
val test1 = { print("無參數(shù)方法") }
/**
*有參數(shù)有返回方法改寫為lambda表達式
*/
fun test2(a: Int, b: Int): Int {
return a + b
}
val test3: (Int, Int) -> Int = { a, b -> a + b }
//可以簡化為
val test4 = { a: Int, b: Int -> a + b }
//認識it
fun test5(){
var array = arrayOf(1,2,3,4,5)
println(array.filter { it < 3 })
}
/**
*認識下劃線
*使用lambda表達式的時候敬特,可以用下劃線(_)表示未使用的參數(shù)掰邢,表示不處理這個參數(shù)
*/
fun test6(){
var map = mutableMapOf<String,String>("a" to "abc","b" to "bcd")
map.forEach { (t, u) -> println(u) }
//用下劃線代替不需要的部分
map.forEach { (_, u) -> println(u) }
}
輸出
Hello Kotlin!
Hello Kotlin From Person
Hello Kotlin From Person companion object
Hello Kotlin! from PersonUtils
Hello Kotlin From 單表達式
abc
magic():36
[1, 2]
abc
bcd
abc
bcd