美文网首页
Kotlin与Java语法对比(首次了解)

Kotlin与Java语法对比(首次了解)

作者: 饮水思源为名 | 来源:发表于2018-10-26 17:42 被阅读24次
    1. 变量的声明。
    //java
    int a;
    int a=0;
    final a=1;
    
    //kotlin
    var a
    var a : Int
    var a=0
    var a : Int =0
    val a=1
    
    1. 字符串拼接:
    //java
    int a=0;
    int b=1;
    String str="a="+a+",b="+b
    
    //kotlin
    var a=0
    var b=1
    var str:String ="a= $a,b= $b"
    
    1. 函数构建
    //java
    public int createFunction(int a,String b){
        return a+b;
    }
    
    //kotlin “?”表示可以返回空值
    fun createFunction(a:int=0,b:String="Hi" ):Int?{
       return a+b
    }
    fun createFunction(a:Int,b:Int)=a+b
    
    1. 使用循环
    //java
    String[] strs={"aa","bb","cc","dd"};
    for(int i=0;i<a.length;i++){
        
    }
    for(String str:strs){
    
    }
    
    //kotlin
     val items = listOf("apple", "banana", "kiwi")
     for (item in items) {
        println(item)
     }
     for (index in items.indices) {
        println("item at $index is ${items[index]}")
     }
    
    1. Kotlin的Win表达式
    fun describe(obj: Any): String =
    when (obj) {
      1          -> "One"
      "Hello"    -> "Greeting"
      is Long    -> "Long"
      !is String -> "Not a string"
      else       -> "Unknown"
    }
    
    fun main(args: Array<String>) {
      println(describe(1))
      println(describe("Hello"))
      println(describe(1000L))
      println(describe(2))
      println(describe("other"))
    }
    
    1. Kotlin的in关键字
    //判断变量是否在range之中
    fun main(args: Array<String>) {
      val x = 10
      val y = 9
      if (x in 1..y+1) {
          println("fits in range")
      }
    }
    fun main(args: Array<String>) {
      val list = listOf("a", "b", "c")
      if (-1 !in 0..list.lastIndex) {
        println("-1 is out of range")
      }
      if (list.size !in list.indices) {
        println("list size is out of valid list indices range too")
      }
    }
    
    //在范围内迭代:
      for (x in 1..5) {
        print(x)
      }
    //或者使用步进:
    for (x in 1..10 step 2) {
        print(x)
      }
      for (x in 9 downTo 0 step 3) {
        print(x)
      }
    //使用 in 操作符检查集合中是否包含某个对象
    val items = setOf("apple", "banana", "kiwi")
    when {
        "orange" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }
    

    相关文章

      网友评论

          本文标题:Kotlin与Java语法对比(首次了解)

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