var sampleString ="Shekhar" if(sampleString.isNotEmpty()){ //the feature of kotlin extension function myTextView.text=sampleString } if(!sampleString.isNullOrEmpty()){ myTextView.text=sampleString }
字符串构造器(Concatenation of strings)
Java
1 2 3
StringfirstName="Amit"; StringlastName="Shekhar"; Stringmessage="My name is: " + firstName + " " + lastName;
Kotlin
1 2 3
var firstName = "Amit" var lastName = "Shekhar" var message = "My name is: $firstName$lastName"
字符串拼接(Substring)
Java
1 2 3
StringfirstName="Amit"; StringlastName="Shekhar"; Stringmessage="My name is: " + firstName + " " + lastName;
Kotlin
1 2 3
val firstName = "Amit" val lastName = "Shekhar" val message = "My name is: $firstName$lastName"
val text = """ |First Line |Second Line |Third Line """.trimMargin()
三元表达式(Ternary Operations)
Java
1
Stringtext= x > 5 ? "x > 5" : "x <= 5";
Kotlin
1 2 3
val text = if (x > 5) "x > 5" else"x <= 5"
比特操作符(Bitwise Operators)
java
1 2 3 4 5 6
finalintandResult= a & b; finalintorResult= a | b; finalintxorResult= a ^ b; finalintrightShift= a >> 2; finalintleftShift= a << 2; finalintunsignedRightShift= a >>> 2;
Kotlin
1 2 3 4 5 6
val andResult = a and b val orResult = a or b val xorResult = a xor b val rightShift = a shr 2 val leftShift = a shl 2 val unsignedRightShift = a ushr 2
类型判断和转换-声明式(Check the type and casting)
Java
1 2 3
if (object instanceof Car) { } Carcar= (Car) object;
Kotlin
1 2 3
if (objectis Car) { } var car = objectas Car
类型判断和转换-隐式(Check the type and casting, implicit)
Java
1 2 3
if (object instanceof Car) { Carcar= (Car) object; }
dataclassDeveloper(var name: String, var age: Int)
// cloning or copying val dev = Developer("Messi", 30) val dev2 = dev.copy() // in case you only want to copy selected properties val dev2 = dev.copy(age = 25)
类方法(Class methods)
Java
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassUtils {
privateUtils() { // This utility class is not publicly instantiable } publicstaticinttriple(int value) { return3 * value; } }
val profile = loadProfiles(context) profile.sortedWith(Comparator({ profile1, profile2 -> if (profile1.age > profile2.age) return@Comparator1 if (profile1.age < profile2.age) return@Comparator -1 return@Comparator0 }))
匿名类(Anonymous Class)
Java
1 2 3 4 5 6 7 8 9 10 11 12 13
AsyncTask<Void, Void, Profile> task = newAsyncTask<Void, Void, Profile>() { @Override protected Profile doInBackground(Void... voids) { // fetch profile from API or DB returnnull; }
@Override protectedvoidonPreExecute() { super.onPreExecute(); // do something } };
Kotlin
1 2 3 4 5 6 7 8 9 10 11
val task = object : AsyncTask<Void, Void, Profile>() { overridefundoInBackground(vararg voids: Void): Profile? { // fetch profile from API or DB returnnull }
overridefunonPreExecute() { super.onPreExecute() // do something } }