kotlin从入门到看开 ₄

2018-10-30  本文已影响11人  東方月初

layout: post
title: "kotlin-程序结构2"
subtitle: "认命就是你和你的自尊心野心不甘心一起围着桌子坐下来 握手言和"


表达式

中缀表达式

class Paper(word: String) {
    var word = word
}

class Pen {
    infix fun on(paper: Paper) {
        if (paper.word.isNotEmpty()) {
            println("Pen on Paper write ${paper.word}")
        } else {
            println("Pen not on Paper")
        }
    }
}

fun main(args: Array<String>) {
    var pen = Pen()
    val paper = Paper("\"Hello infix\"")
    pen on paper
}

if 表达式

val s:Int = if (paper.word.isEmpty()){
        0
    }else{
        1
    }

when 表达式

例一

fun main(args: Array<String>) {
    val x = 5
    when (x) {
        is Int -> println("Hello $x")
        in 1..100 -> println("$x is in 1..100")
        !in 1..100 -> println("$x is not in 1..100")
        args[0].toInt() -> println("x == args[0]")
    }

    val mode = when {
        args.isNotEmpty() && args[0] == "1" -> 1
        else -> 0
    }
}

例二

class Player {
    enum class State {
        IDLE, BUFFERING, PLAYING, PAUSED
    }

    private var state = State.IDLE


    fun pause() {
        when (state) {
            Player.State.BUFFERING, Player.State.PLAYING -> doPause()
            else -> {

            }
        }
    }

    fun resume() {
        when (state) {
            Player.State.PAUSED -> doResume()
        }//什么都不做
    }

    private fun doResume() {
        state = State.PLAYING
        //处理真正的继续播放逻辑
    }

    private fun doPause() {
        state = State.PAUSED
        //处理真正的暂停逻辑
    }
}

循环语句

for 循环

    val listInt = listOf(1, 2, 4, 5)
    for (i in listInt){
        println(i)
    }

跳过和终止循环

   val listInt = listOf(1, 2, 4, 5,7,9,23)
    Outer@for (i in listInt){
        println(i)
        Inner@while (i>5){
            break@Outer
        }
    }

异常捕获

 try {
        val arg1 = args[0].toInt() //1
        val arg2 = args[1].toInt() //2a
        println("$arg1 + $arg2 = ${sum(arg1, arg2)}")
    }catch (e: NumberFormatException){
        println("您确定输入的是整数吗?")
    }catch (e: ArrayIndexOutOfBoundsException){
        println("您确定输入的是两个整数吗?")
    }catch (e: Exception){
        println("程序出现了未知异常,可能是您的人品太差了.${e.message}")
    }finally {
        println("谢谢您使用我们的加法计算器")
    }

具名参数

具名参数 : 给函数的实参附上形参

fun sum(args1:Int,args2:Int)=args1+args2
sum(args1=2,args2=3)//此时args2=3在前在后编译器都知道3是给args2的

变长参数

fun main(vararg args: String) {

    val list = arrayListOf(1,3,4,5)
    val array = intArrayOf(1,3,4,5)
    //*array 目前只支持数组 只用于变长参数列表展开数组
    hello(3.0, *array)
}

fun hello(double: Double, vararg ints: Int, string: String = "Hello"){
    println(double)
    ints.forEach(::println)
    println(string)
}

默认参数

上一篇下一篇

猜你喜欢

热点阅读