原文地址

From Java to Kotlin

Print

System.out.println("Hello World!");
println("Hello World!")

Constant and Variable

int a = 10;
final int a = 10;
var a = 10
val a = 10

Assigning the null value

String name = null;
var name: String? = null

verify if value is null

if (name != null){
       int length = name.length();
}
name?.let {
    val length = it.length
}
// or
val length = name?.length ?: 0

verify if value is NotNull or NotEmpty

String name = "111"
if (!name.isEmpty()){
    int length = name.length();
}
if (name != null && !name.isEmpty()){
    int length = name.length();
}
var name = "111"
if (name.isNotEmpty()){
    val length = name.length
}
if (!name.isNullOrEmpty()){
    val length = name.length
}

concatenation of strings

String firstName = "Amit";
String lastName = "Shekhar";
String message = "My name is " + firstName + " " + lastName;

// or
StringBuilder sb = new StringBuilder("My name is ");
sb.append(firstName).append(" ").append(lastName);
message = sb.toString();
val firstName = "Amit"
val lastName = "Shekhar"
val message = "My name is $firstName $lastName"

new line in string

String text = "First line\n" +
    "Second line";
val text = """
    |First line
    |Second line
    """.trimMargin()

Substring

String str = "java to kotlin guide";

String subStr = str.substring(0,4);
System.out.println(subStr);

subStr = str.substring(8,14);
System.out.println(subStr);
val str = "java to kotlin guide"

var subStr = ""
subStr = str.substring(0..3)
println("substring$subStr")

subStr = str.substring(8..13)
println("substring$subStr")

Ternary Operations 三元运算

int x = 10;
String text = x > 5 ? "x is greater than 5" : "x is not greater than 5";
System.out.println(text);
String message = null
log(message != null ? message:"")
val x = 10
val text = if (x > 5) "x is greater than 5" else "x is not greater than 5"
println(text)
val message: String? = null
println(message ?: "")

Bitwise Operations 位运算

final int andResult  = a & b;
final int orResult   = a | b;
final int xorResult  = a ^ b;
final int rightShift = a >> 2;
final int leftShift  = a << 2;
final int unsignedRightShift = a >>> 2;
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

if (a instanceof Integer) {
    Integer i = (Integer) a;
}
if (a is Int) {
    val i as a
}
// if a is null
var i = a as? Int // var i = a as Int?

Check the type and casting (implicit)

if (a instanceof Integer) {
    Integer i = a;
}
if (a is Int) {
    val i = a
}
// if a is null
if ( a is Int?){
    var i = a 
}

Multiple conditions 多重条件

if (score >= 0 && score <= 300) { }
if (score in 0..300) { }

Multiple Conditions (Switch case)

switch (score) {
    case 0:
        System.out.println("Score is 0");
        break;
    case 1:
        System.out.println("Score is 1");
        break;
    case 2:
        System.out.println("Score is 2");
        break;
    default:
        System.out.println("Score is unknown");
        break;
}
val score = 100
when (score) {
    0 -> println("Score is 0")
    1,2 -> println("Score is 1")
    in 3..10 -> println("Score is 2")
    4,5 -> println("Score is 3")
    else -> println("Score is unknown")
}

For-loops

for (int i = 0; i < 10; i++){}
for ( int i : intArray){}
for ( Map.Entry<String, String> entry: map.entrySet()){}
for (i in 0..9) {}
for ( i in 1 until 9){}
for (i in 9 downTo 0){}
for (i in 1..10 step 2){}
for (i in 10 dowTop 0 step 2){}
for (item in intArray){}
for ((key, value) in map){}

Collections

final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);

final Map<Integer, String> keyValue = new HashMap<Integer, String>();
map.put(1, "Amit");
map.put(2, "Anand");
map.put(3, "Messi");

// Java 9
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);

final Map<Integer, String> keyValue = Map.of(1, "Amit",
                                             2, "Anand",
                                             3, "Messi");
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Amit",
                     2 to "Anand",
                     3 to "Messi")

for each

for (Car car : cars) {
  System.out.println(car.speed);
}

cars.forEach(car -> System.out.println(car.speed));

for (Car car : cars) {
  if (car.speed > 100) {
    System.out.println(car.speed);
  }
}

cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));
cars.parallelStream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));

cars.forEach {
    println(it.speed)
}

cars.filter { it.speed > 100 }
      .forEach { println(it.speed)}


cars.stream().filter { it.speed > 100 }.forEach { println(it.speed)}
cars.parallelStream().filter { it.speed > 100 }.forEach { println(it.speed)}

splitting arrays

String[] splits = "param=car".split("=");
String param = splits[0];
String value = splits[1];
val (param, value) = "param=car".split("=")

defining methods

void doSomeThing() {
    // xx
}
fun doSomeThing() {
    // xx
}

default values for method parameters

double calculateCost(int quantity, double pricePerItem) {
    return pricePerItem * quantity;
}

double calculateCost(int quantity) {
    // default price is 20.5
    return 20.5 * quantity;
}
fun calculateCost(quantity: Int, pricePerItem: Double = 20.5) = quantity * pricePerItem

calculateCost(10, 25.0) // 250
calculateCost(10) // 205

variable number of arguments

void doSomeThing(int... args) {
    for (int arg : args) {
        System.out.println(arg);
    }
}

doSomeThing(1, 2, 3)
fun doSomeThing(vararg args: Int) {
    for (arg in args) {
        println(arg)
    }
}
doSomeThing(1, 2, 3)

Defining methods with return

int getScore() {
   // logic here
   return score;
}
fun getScore(): Int {
   // logic here
   return score
}
fun getScore(): Int = score
fun getScore() = score // return-type is Int

returning result of an operation

int getScore (int value) {
    return 2 * value;
}
fun getScore(value: Int): Int {
    return 2 * value
}
fun getScore(value: Int): Int = 2 * value
fun getScore(value: Int) = 2 * value

constructors

public class Utils {
    private Utils() {

    }
    public static int getScore(int value) {
        return 2 * value;
    }
}
class Utils private constructor() {

    companion object {

        fun getScore(value: Int): Int {
            return 2 * value
        }

    }
}

// another way

object Utils {

    fun getScore(value: Int): Int {
        return 2 * value
    }

}

getter or setter

public class Car {
    private int speed;
    public int getSpeed() {
        return speed;
    }
    public void setSpeed(int speed) {
        this.speed = speed;
    }
}
data class Car(var speed: Int) {
}

cloning or copying

public class Developer implements Cloneable {

    private String name;
    private int age;

    public Developer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return (Developer)super.clone();
    }
}

// cloning or copying
Developer dev = new Developer("Messi", 30);
try {
    Developer dev2 = (Developer) dev.clone();
} catch (CloneNotSupportedException e) {
    // handle exception
}

data class Developer(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)

泛型

interface SomeInterface<T>{
    void doSomeThing(T t);
}
class SomeClass implements SomeInterface<Integer> {
    @Override
    public void doSomeThing(Integer t) {
        // xx
    }
}
interface SomeInterface<T extends Collection<?>> {
    void doSomeThing(T t);
}
class SomeClass implements SomeInterface<List<String>> {
    @Override
    public void doSomeThing(List<String> t) {
        // xx
    }
}
interface SomeInterface<T> {
    fun doSomeThing(t: T)
}
class SomeClass : SomeInterface<Int> {
    override fun doSomeThing(t: Int) {
        // xx
    }
}
interface SomeInterface<T : Collection<*>> {
    fun doSomeThing(t: T)
}
class SomeClass : SomeInterface<List<String>> {
    override fun doSomeThing(t: List<String>) {
        // xx
    }
}

extension function

public class Utils {

    private Utils() {
      // This utility class is not publicly instantiable
    }

    public static int triple(int value) {
        return 3 * value;
    }

}

int result = Utils.triple(3);
fun Int.triple(): Int {
  return this * 3
}

var result = 3.triple()

defining uninitialized objects

Person person;
internal lateinit var person: Person;

enum

public enum Color {
    RED(0), GREEN(1), BLUE(2)

    int color;
    Color(int color) {
        this.color = color;
    }
    public int getColor() {
        return color;
    }
}
enum class Color(val color: Int) {
    RED(0), 
    GREEN(1), 
    BLUE(2)
}

sorting list

List<Profile> profiles = loadProfiles(context);
Collections.sort(profiles, new Comparator<Profile>() {
    @Override
    public int compare(Profile profile1, Profile profile2) {
        if (profile1.getAge() > profile2.getAge()) return 1;
        if (profile1.getAge() < profile2.getAge()) return -1;
        return 0;
    }
});
Collections.sort(profiles,(p1,p2)->p1.getAge()-p2.getAge());
Collections.sort(profiles, Comparator.comparingInt(Profile::getAge));
val profile = loadProfiles(context)
profile.sortedWith(Comparator({ profile1, profile2 ->
    if (profile1.age > profile2.age) return@Comparator 1
    if (profile1.age < profile2.age) return@Comparator -1
    return@Comparator 0
}))
profile.sortedWith{p1,p2->p1.age-p2.age}
profiles.sortedBy { it.age }

anonymous class

 AsyncTask<Void, Void, Profile> task = new AsyncTask<Void, Void, Profile>() {
    @Override
    protected Profile doInBackground(Void... voids) {
        // fetch profile from API or DB
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // do something
    }
};
val task = object : AsyncTask<Void, Void, Profile>() {
    override fun doInBackground(vararg voids: Void): Profile? {
        // fetch profile from API or DB
        return null
    }

    override fun onPreExecute() {
        super.onPreExecute()
        // do something
    }
}

initialization block

public class SomeClass {
    {
        // initialization block
    }
}
class SomeClass {
    init {
        // initialization block
    }
}
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐