Kotlin学习(1)概述

变量和常量

//String类型,自动判断类型(不可变变量Value)
val laugh = "lalalalala"
//浮点类型,默认Double
val PI = 3.1415
//Float类型
val PI_FLOAT = 3.1415F
//一旦赋值后不能改变,但是可以条件赋值
val msg: Int = min(2,1)


//可变类型(Variable)
var status = 0
fun block(){
    //但类型不能改变,以下语句报错
    //status = "aaa"
}

函数

//参数和返回值都是写在: 后面
fun max(a: Int, b: Int): Int {
    //if...else可代替?:
    return if (a > b) a else b
}

//函数也不用写在里面
//短函数块,还是能用=
fun min(a: Int, b: Int): Int = if (a > b) b else a

类的定义

/**
class Test(val name: String = "Test")
==>等价于
public class Person{
    private final String name;

    public Person(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }
}

//val只有getter方法
//var有getter和setter方法
 */

//这是个默认构造器,并且可以赋个默认值
class Test(val name: String = "Test") {

    //参数和返回值都是写在: 后面
    fun max(a: Int, b: Int): Int {
        //if...else可代替?:
        return if (a > b) a else b
    }
}

class Rectangle(val height: Int, val width: Int){
    //自定义getter方法
    val isSquare: Boolean
        get() = height == width
}
fun createRec(): Rectangle{
    val random = Random()
    return Rectangle(random.nextInt(),random.nextInt())
}

main函数和模板字符串

//main函数已经不能写在Class里面了
fun main(args: Array<String>) {
    val max = Test().max(1,2)  //和Java类似

    //字符串模板
    println("The max is $max")
    println("The min is ${min(1,2)}")
    println(max is Int)               //类似于instanceof
}

继承和接口

interface Expr

class Num(val value: Int) : Expr

class Sum(val left: Expr, val right: Expr) : Expr

fun eval(e: Expr): Int{
    if (e is Num){
        //此处不用显性类型转化
        val n = e //as Num
        return n.value
    }
    if (e is Sum){
        //在e is Sum为True时,该作用域内自动转化
        return eval(e.left) + eval(e.right)
    }
    throw IllegalArgumentException()
}

fun eval2(e: Expr): Int =
        when (e){
            is Num -> {
                println("num: ${e.value}")
                e.value
            }
            is Sum -> {
                val left = eval2(e.left)
                val right = eval2(e.right)
                println("sum: $left + $right")
                left + right
            }
            else -> throw IllegalArgumentException()
        }


fun main(args: Array<String>){
    val a = eval2(Sum(Sum(Num(1),Num(2)),Num(4)))
    println(a)
}

Enum和when

//枚举类
enum class Color (
        val r: Int,
        val g: Int,
        val b: Int
){
    RED(255,0,0),
    ORANGE(255,165,0),
    GREEN(0,255,0),
    YELLOW(0,0,255),
    BLUE(0,0,255),
    JAOSDHO(161,18,25);

    fun rgb() = (r * 256 + g) * 256 + b

    //when来代替switch
    fun getMnemonic(color: Color) =
            when (color){
                BLUE -> "Blue"
                GREEN -> "Green"
                ORANGE,RED -> "Red or Orange"
                else -> "fuck color"
            }

    fun mixColor(c1: Color, c2: Color) =
            when (setOf<Color>(c1, c2)){
                setOf(RED,YELLOW) -> ORANGE
                setOf(YELLOW,BLUE) -> GREEN
                else -> throw Exception("Unknown Color")
            }

    fun maxColor2(c1: Color, c2: Color): Color{
        when{
            (c1 == RED && c2 == YELLOW) ||
                    (c1 == YELLOW && c2 == RED) ->
            return ORANGE

            else -> throw Exception("Unknown Color")
        }
    }
}

迭代和in

可以使用传统的while(){…}或do{…}while()
fun main(args: Array<String>){

    //class kotlin.ranges.IntRange
    val oneToTen = 1..10            //包括10
    val oneToSize = 1 until 10      //不包括10
    val tenToOne = 10 downTo 1      //包括1
    val stepTwo = 1..10 step 2      //1,3,5,7,9

    //class kotlin.ranges.CharRange
    val charIter = 'A'..'F'

    //test IntRange
    for (i in stepTwo){
        //println(i)
    }


    //Map上的迭代
    val sortedMap = TreeMap<Char,String>()
    //test Map
    for (c in 'A'..'F'){
        //可以以Python的方式访问和赋值
        sortedMap[c] = Integer.toBinaryString(c.toInt())
    }
    for ((k,v) in sortedMap){
        println("$k = $v")
    }


    //List上的迭代
    val list = arrayListOf("10","11","1001")
    for ((index,ele) in list.withIndex()){
        println("$index : $ele")
    }

    //使用in来判断,使用的是Comparable接口的c
    fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z'
    fun isNotDigit(c: Char) = c !in '0'..'9'
    println("KCK" in "J".."L")                  //true,K在J,L中间
    println("Kotlin" in setOf("Java","Scala"))  //false


}

try…catch…finally

可以和Java一样的用法
或作为表达式
fun readNumber(read: BufferedReader){
    //try{}作为表达式
    val number = try {
        Integer.parseInt(readLine())
    }catch (e: NumberFormatException){
        return
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值