var score = // some score
var grade = when (score) {
9, 10 ->"Excellent"in6..8 ->"Good"4, 5 ->"OK"in1..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) { }
for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
for (i in1..10) { }for (i in1until10) { }for (i in10downTo0) { }for (i in1..10step2) { }for (i in10downTo1step2) { }for (item in collection) { }for ((key, value) in map) { }
class Utils privateconstructor(){
companion object {
fun getScore(value: Int): Int {
return 2 * value
}
}
}
//另一种方式
objectUtils{
fun getScore(value: Int): Int {
return 2 * value
}
}
Get Set 构造器
Java
publicclassDeveloper {private String name;
privateint age;
publicDeveloper(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
publicintgetAge() {
return age;
}
publicvoidsetAge(int age) {
this.age = age;
}
@Overridepublicbooleanequals(Object o) {
if (this == o) returntrue;
if (o == null || getClass() != o.getClass()) returnfalse;
Developer developer = (Developer) o;
if (age != developer.age) returnfalse;
return name != null ? name.equals(developer.name) : developer.name == null;
}
@OverridepublicinthashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Overridepublic String toString() {
return"Developer{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Kotlin
data class Developer(valname: String, valage: Int)
Java
publicclassUtils {privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticinttriple(int value) {
return3 * value;
}
}
int result = Utils.triple(3);
Kotlin
fun Int.triple(): Int {
returnthis * 3
}
var result = 3.triple()