美文网首页
Kotlin入门语法

Kotlin入门语法

作者: 一点墨汁 | 来源:发表于2017-06-07 13:12 被阅读85次

    变量:var
    常量: val

    Java 常用变量定义

        private int number = 2;
        private int[] numbers = new int[2];
        private int[][] intNumbers = new int[2][2];
    
        private String nullStr = null;
        private String str = "hello kotlin";
        private String[] strs = {"first","second","third"};
    
        private Map<String,String> map = new HashMap<String,String>(); 
        private List<String> list = new ArrayList<String>();
    

    Code->Convert to Java以后Kotline 常用变量定义

        private val number = 2
        private val numbers = IntArray(2)
        private val intNumbers = Array(2) { IntArray(2) }
    
        private val nullStr: String? = null
        private val str = "hello kotlin"
        private val strs = arrayOf("first", "second", "third")
    
        private val map = HashMap<String, String>()
        private val list = ArrayList<String>()
    

    When 的使用处理,可处理常量,表达式,可替代if...else if.. else ...

       var x = 10
        when (x) {
            5 -> println("x等于5")    
            if (x > 0) 5 else 0 -> println(">0赋值为5,或小于0赋值为0")
            in 1..5 -> println("在[1,5]之间")          //闭区间
            in 1 until 5 -> println("在[1,5)之间")   //半开区间
            !in 6..9 -> println("不在6~9之间")
            is Int -> println("是整型")
            else -> println("默认处理")
        }
    
        when (x) {
            in 7..10 -> println("在(6,10]之间")
            if(x <= 6) 6 else x ->println("<=6")
            else -> println("else")
        }
    

    for循环的使用

      for (i in list.indices){
            println(list[i])
        }
        //    for(int i=0; i<list.size; i++)
        for (i in 2..list.size-1){
            println(list[i])
        }
        //    for(int i=size-1; i>=0; i--)
        for (i in list.size-1 downTo 0){
            println(list[i])
        }
        for(i in list.size-1 downTo 0 step 2){
            println(list[i])
        }
    
        for (item in list){
            println(item)
        }
        for ((i,item) in list.withIndex()){
            print(list[i])
            print("->"+item)
        }
        list.forEach { println(it) }
    

    使用lambda表达式过滤和映射集合

       val fruits = listOf("apple", "banana", "kiwi", "avocado")
       fruits.filter { it.startsWith("a") }
             .sortedBy { it }
             .map(String::toUpperCase)
             .forEach(::println)
    

    函数默认值

    fun foo(a:Int = 0, b:String=""){...}
    

    List过滤

    val filters = list.filter{ x -> x>0 }
    val filters = list.filter{ it > 0}
    

    实例检查

    when ( x ){
      is Foo -> ...
      is Bar -> ...
      else -> ...
    }
    

    遍历 Map /List

    val map = mapOf("a" to 1, "b" to 2, "c" to 3)
    for((k,v) in map){ print ("$k" -> "$v") }
    
    //访问map
    println(map["key"])
    map["key"]=value
    
    

    扩展函数

    fun String.spaceToCamelCase(){...}
    "test String".spaceToCamelCase()
    

    创建单例模式

    object Singleton{ val name = "Name"}
    

    为空判断

    ?.   不为空
    ?:   为空
    
    val files = File("Test").listFiles()
    println(files?.size)                      // 如果不为空就...
    println(files?.size ?: "empty")    // 如果不为空就...,否则为空就...
    println(files ?: throw IllegalStateException(" is null"))  // 为空,执行...
    
    val data = ...
    data ?.let{  ... }    // 如果不为空执行某操作
    

    try-catch

    fun test(){
      val result = try{
          count()
        }catch(e: Exception){
          throw Exception(e)
        }
    }
    

    if ...else

    fun foo(param:Int){
        val result =
                if(param == 1){
                    "one"
                }else if(param == 2){
                    "two"
                }else{
                    "three"
                }
        println(result)
    }
    

    利用with关键词来调用一个对象实例的多个方法

    class Turtle{
       fun penDown()
       fun penUp()
       fun turn (degress: Double)
       fun forward(pixels: Double)
    }
    val myTurtle = Turtle()
    with(myTurtle){
       penDown()
       for( i in 1..4){
          forward( 100)
          turn(90)
       }
       penUp()
    }
    

    Java 7’s try with resources

    val stream = Files.newInputStream(Paths.get("/Users/liupengfei/Desktop/Kotlin/src/file.txt"))
        stream.buffered().reader().use {
            reader -> println(reader.readText())
        }
    

    需要泛型信息的泛型函数的表达形式

    //  public final class Gson {
    //     ...
    //     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
    //     ...
    
    inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json,T::class.java)
    

    相关文章

      网友评论

          本文标题:Kotlin入门语法

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