Kotlin之方法

2020-09-21  本文已影响0人  xu_pan
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")
    }

    //伴随对象中的方法可以直接调用
    companion object {
        fun sayHello2(name: String) {
            println("Hello $name From Person companion object")
        }
    }
}

//类似于Java中的静态方法
object PersonUtils {
    fun sayHello(name: String) {
        println("Hello $name! from PersonUtils")
    }
}

/**
 *单表达式方法,当方法仅有单个表达式时,可以省略花括号,并在 = 后指定方法体即可
 */
fun sayHelloSingle(name: String) = println("Hello $name From 单表达式")

/**
 *默认值,方法参数可以有默认值,当省略相应参数时使用默认值。与Java相比,可以减少重载数量
 */
fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {

}

/**
 * 可变数量参数
 */
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)
}

/**
 * 无参数方法改写为lambda表达式
 */
fun test() {
    println("无参数方法")
}

val test1 = { print("无参数方法") }

/**
 *有参数有返回方法改写为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表达式的时候,可以用下划线(_)表示未使用的参数,表示不处理这个参数
*/
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
上一篇 下一篇

猜你喜欢

热点阅读