Kotlin基础

来源:互联网 发布:ios 数组转json字符串 编辑:程序博客网 时间:2024/05/14 02:29

1.函数

a.语句式函数

fun 函数名称(参数列表):返回类型{
      函数体
}

b.表达式函数

fun 函数名称(参数列表):返回类型 = 表达式
fun 函数名称(参数列表) = 表达式

fun main(args:Array<String>){    println(max1(4,5))}fun max1(a:Int,b:Int) = if(a>b) a else bfun max2(a:Int,b:Int):Int{    return if(a>b) a else b}

2.变量

a.不可变变量:val

b.可变变量:var

3.字符串模板

a. ${变量名}

b. ${表达式}

fun main(args:Array<String>){    val name = if (args.size > 0) args[0] else "Kotlin"    println("Hello,${name}")}

4.类

a.简单类

class Person (val name : String)

b.属性

只读属性:val
可变属性:var

class Person (    val name : String    var isMarried: Boolean)

c.自定义访问器

class Rectangle(val height:Int,val width:Int) {    val isSquare:Boolean        get() {return height == width}        //get() = height == width}

d.使用类

val rectangle = Rectangle(41,42)println(rectangle.isSquare)

5.枚举

a.简单枚举

enum class Color {    RED,ORANGE,YELLOW,GREEN,BLUE,INDIGO,VIOLET}

b.带属性枚举

enum class Color (val r:Int,val g:Int,val b:Int){    //注意分号    RED(255,0,0),ORANGE(255,165,0),BLUE(0,0,255);    fun rgb() = (r * 256 +g) * 256 + b}

使用
println(Color.RED.rgb())

6.when

a.使用when选择正确枚举值

fun getMnemonic(color:Color) =        when (color){            Color.RED -> "Red"            Color.ORANGE -> "Orange"            Color.BLUE -> "Blue"        }

println(getMnemonic(Color.BLUE))

b.一个when上合并多个分支

fun getMnemonic(color:Color) =        when (color){            Color.RED,Color.ORANGE -> "OrangeRed"            Color.BLUE -> "Blue"        }

c.在when结构中使用任意对象

fun mix(c1:Color,c2:Color) =         when(setOf(c1,c2)){            setOf(Color.RED,Color.BLUE) -> Color.BLUE            setOf(Color.RED,Color.ORANGE) -> Color.ORANGE            else -> throw Exception("error")        }

d.when不带参数下分支条件是布尔表达式

fun mix(c1:Color,c2:Color) =         when{            (布尔条件式1) -> Color.BLUE            (布尔条件式2) -> Color.ORANGE            else -> throw Exception("error")        }

e.智能转换:合并类型检查和转换

背景:

数值求和

interface Exprclass Num(val value:Int) : Exprclass Sum(val left:Expr,val right:Expr) : Expr

java风格下求值函数

fun eval(e:Expr): Int {    if(e is Num) {        val n = e as Num        return n.value    }    if(e is Sum){        return eval(e.left) + eval(e.right)    }    throw IllegalAccessException("Unknown Expression")}

重构1: 不用return(if有返回值)

重构2:用when替换if

fun eval(e:Expr): Int =    when (e){        is Num ->{            e.value        }        is Sum ->{            eval(e.left) + eval(e.right)        }        else ->            throw IllegalAccessException("Unknown Expression")     }

技巧:代码块作为if和when的分支

7.迭代

a.迭代数字:区间和数列

闭区间

使用..运算符表示区间 val oneToTen = 1..10

迭代带步长的区间(100 downTo 1 是递减数列,步长step为2)

for(i in 100 downTo 1 step 2){}

不包含结束值的半闭合区间

for(x in 0 until size) 等同于 for(x in 0 .. size - 1)

b.迭代map

fun interMap(){    val binaryReps = TreeMap<Char,String>()    for (c in 'A'..'F'){        val binary = Integer.toBinaryString(c.toInt())        binaryReps[c] = binary    }    for((letter,binary) in binaryReps){        println("$letter = $binary")    }}

c.使用in检查集合和区间成员

fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z'fun isNotDigit(c: Char) = c !in '0'..'9'fun recognize(c: Char) = when(c) {    in '0'..'9' -> "digit!"    in 'a'..'z', in 'A'..'Z' ->"letter!"    else -> "don't know!"}

8.异常

throw

throw是一个表达式

try,catch,finally

try,catch都是表达式

fun readNumber(reader: BufferedReader): Int? {    try {        val line = reader.readLine()        return Integer.parseInt(line)    }    catch (e: NumberFormatException){        return null    }    finally {        reader.close()    }}
原创粉丝点击