美文网首页
Kotlin实战读书笔记(二 基础)

Kotlin实战读书笔记(二 基础)

作者: Pyrrha_89c6 | 来源:发表于2017-12-05 00:33 被阅读0次
  1. 函数和变量
  • 函数基本结构
    fun max(a: Int,b: Int): Int {  // if是表达式(有值的是表达式)
      return if(a>b) a else b
    }
    
  • 表达式函数体
    fun max(a: Int,b: Int): Int = if(a > b) a else b 
                    ==
    fun max(a: Int,b: Int) = if(a > b) a else b 
    
  • 可便变量 val(value) 不可变引用,var(variable)可变引用
    • 尽量使用 val
    val message: String     // 不可变引用可根据条件赋值
    if (canPerformOperation()){
         message = "Success"
        // do something
    }else{ message = "Failed" }
    
  • 字符串模板
    "Hello,$name"  = ”Hello,${name}"
    "Hello,${obj.name}"
    "Hello, ${ if (array.size > 0)  array[0] else "Guest" }" //在花括号类使用引号
    
  1. 类和属性
  • 值对象
    public class Person {  // java
      private final String name;
      public Person(String name) {
          this.name = name;
      }
      public getName(){ return name; }
    }
                  ==
    class Person(val name: String)  //kotlin
    
  • 属性
    class Person( 
        val name: String, //只读,有getter方法
        var isMarried: Boolean //可变,有getter、setter方法
    )
    
  • 自定义访问器
    class Rectangle(val height: Int, var width: Int){
        val isSquare: Boolean
            get(){ return height == width }
    }
    
  • 导入和Java差不多,增加了kotlin的顶层函数和方法而已
  • kotlin一个文件可以放多个类,名字也不必和文件名对应,由于kotlin有很多小类,建议将多个小类放在一个文件
  1. 表示和处理选择: 枚举和“when”
  • 枚举类
    enum class Color { RED,ORANGE,BLUE} //  enum 在class前面才是关键字,所以可做变量名
    enum class Color( val r: Int, val g: Int , val b: Int){
        RED(255,0,0),ORANGE(255,165,0); //kotlin唯一必须使用分好的地方,在枚举类中将属性和方法分隔开
        fun rgb() = (r * 265 +g)* 265 + b
    }
    
  • 用when处理枚举类
    fun getWarmth(color: Color) = when(color){
        Color.RED,Color.ORANGE -> "warm"
        Color.BLUE -> "cold"
    }
    import package.Color.* //导入Color的常量
    fun getWarmth(color: Color) = when(color){
          RED,ORANGE -> "warm" 
          BLUE -> "cold"
    }
    
  • when中使用任意对象
    fun mix(c1: Color,c2: Color) = when (setOf(c1,c2)){
          setOf(RED,YELLOW) -> ORANGE
          setOf(BLUE,YELLOW) -> GREEN
          else -> throw Exception("Dirty color")
    }
                    ==
    fun mixOptimized(c1: Color,c2: Color) = when{ //when没传参
        c1 == RED && c2 ==YELLOW || c1 == YELLOW && c2 ==RED -> ORANGE
        c1 == BLUE && c2 ==YELLOW || c1 == YELLOW && c2 ==BLUE -> ORANGE
        else -> throw Exception("Dirty color")
    }
    
  • 智能转换:
    (1+2)+4 = 7 :
    
    interface Expr
    class Num(val value: Int): Expr
    class Sum(val left: Expr,val right: Expr):Expr
    fun eval(e: Expr) : Int = when(e){
        is Num -> { 
            // do something
            e.value  //不用像java一样判断了类型还要强转
        } 
        is Sum -> eval(e.left) + eval(e.right)
        else -> throw IllegalArgumentException("Unknown expression")
     }
    eval(Sum(Sum(Num(1),Num(2)),Num(4))) // = 7
    
  1. 迭代
  • while循环和Java一样
  • 区间:
    1..10  // 1-10,闭合的区间
    100 downTo 1 step 2  // 100-1的偶数
    0 until size == 0...size-1
    'A'..'Z' // A到Z的字符区间
    
  • 迭代区间: for( x in 1..10)
  • 迭代Map
    for((key,value) in map) {
        value == map[key] // map[key] == map.get(key)
        map[key] = newVal // == map.put(key,newVal)
    }
    
  • 迭代数组
    for( item in list)
    for((index,item) in list.withIndex()) //带下标迭代数组
    
  • in 运算符(可用于判断,也可用于when表达式)
    'c' in 'a'..'z' // true 底层实现:'a' <= 'c' && 'c' <= 'z'
    'c' !in '0'..'9' // false
    param in comparable1..comparable2 // in表达式对实现了comparable的所有对象有效
    
  1. 异常处理
    和java的不同点:
    • throw结构是一个表达式
    val value = if ( number in 0..100) number else throw IllegalArgumentException("$number not in 0..100")
    
    • kotlin不用区分受检异常和不受检异常,比如不用显式处理IOException
    • try做表达式
    val number = try { // number = null
          Integer.parseInt("not a number")
      }catch (e: Exception){
          null 
      }  
    

相关文章

网友评论

      本文标题:Kotlin实战读书笔记(二 基础)

      本文链接:https://www.haomeiwen.com/subject/hwofixtx.html