常量与变量
java
String name = "Pan Zhou";
final String name = "Pan Zhou";
kotlin
var name = "Pan Zhou"
val name = "Pan Zhou"
null声明
java
String otherName;
otherName=null;
kotlin
var otherName : String?
otherName = null
空判断
java
if (text != null) {
int length = text.length();
}
kotlin
text?.let {
val length = text.length
}
// 或者
val length = text?.length
字符串拼接
java
String a ="a";
String b = "b";
String message = a+b;
kotlin
var a = "a";
var b = "b";
var message = $a $b
三元运算符
java
String num = x > 5 ? "x > 5" : "x <= 5";
kotlin
var num = if(x>5)
"x>5"
else "x<5"
操作符
java
final int andResult = a & b;
final int orResult = a | b;
kotlin
val andResult = a and b
val orResult = a or b
多重条件
java
if (score >= 0 && score <= 300) { }
kotlin
if (score in 0..300) { }
Case语句
java
int score = // some score;
String grade;
switch (score) {
case 10:
case 9:
grade = "Excellent";
break;
case 8:
case 7:
case 6:
grade = "Good";
break;
case 5:
case 4:
grade = "OK";
break;
case 3:
case 2:
case 1:
grade = "Fail";
break;
default:
grade = "Fail";
}
kotlin
var score = // some score
var grade = when (score) {
9, 10 -> "Excellent"
in 6..8 -> "Good"
4, 5 -> "OK"
in 1..3 -> "Fail"
else -> "Fail"
}
for循环
java
for (int i = 1; i <= 10 ; i++) { }
for (int i = 1; i < 10 ; i++) { }
for (int i = 10; i >= 0 ; i--) { }
for (int i = 1; i <= 10 ; i+=2) { }
for (int i = 10; i >= 0 ; i-=2) { }
for (String item : collection) { }
kotlin
for (i in 1..10) { }
for (i in 1 until 10) { }
for (i in 10 downTo 0) { }
for (i in 1..10 step 2) { }
for (i in 10 downTo 0 step 2) { }
for (item in collection) { }
遍历
java
for (Car car : cars) {
if (car.speed > 100) {
System.out.println(car.speed);
}
}
kotlin
cars.filter { it.speed > 100 }
.forEach { println(it.speed)}
方法定义
java
void doSomething() {
// logic here
}
void doSomething(int... numbers) {
// logic here
}
kotlin
fun doSomething() {
// logic here
}
fun doSomething(vararg numbers: Int) {
// logic here
}
带返回值的方法
java
int getScore() {
// logic here
return score;
}
kotlin
fun getScore(): Int {
// logic here
return score
}
//动态添加数组
val emptyArr = arrayOfNulls<String>(categoryList.size)
for (i in categoryList.indices){
emptyArr[i] = categoryList[i].name
}
网友评论