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

  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
//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) {
  println(describe(1))
  println(describe("Hello"))
  println(describe(1000L))
  println(describe(2))
  println(describe("other"))
}
  1. Kotlin的in关键字
//判断变量是否在range之中
fun main(args: Array) {
  val x = 10
  val y = 9
  if (x in 1..y+1) {
      println("fits in range")
  }
}
fun main(args: Array) {
  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语法对比(首次了解))