(Basic) Từ JAVA sang Kotlin sẽ như thế nào (Part 1)

Các cú pháp cơ bản giữa java và kotlin part 1.

1. Cú pháp Print

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

2. Variables I

final int x;
final int y = 1;
val x: Int
val y = 1

3.Variables II

int w;
int z = 2;
z = 3;
w = 1;
var w: Int
var z = 2
z = 3
w = 1

4.Null I

final String name = null;

String lastName;
lastName = null
val name: String? = null

var lastName: String?
lastName = null

var firstName: String
firstName = null // Compilation error!!

5.Null II

if(text != null){
  int length = text.length();
}
val length = text?.length

val length = text!!.length // NullPointerException if text == null

6.Strings I

String name = "John";
String lastName = "Smith";
String text = "My name is: " + name + " " + lastName;
String otherText = "My name is: " + name.substring(2);
val name = "John"
val lastName = "Smith"
val text = "My name is: $name $lastName"
val otherText = "My name is: ${name.substring(2)}"

7.Strings II

String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";
val text = """
        |First Line
        |Second Line
        |Third Line
""".trimMargin()
8.Ternary Operator
String text = x > 5 ? "x > 5" : "x <= 5";
val text = if (x > 5)
              "x > 5"
            else "x <= 5"

9.Is As In

if(x instanceof Integer){ }

final String text = (String) other;

if(x >= 0 && x <= 10 ){}
if (x is Int) { }

val text = other as String

if (x in 0..10) { }

10.Smart Cast

if(a instanceof String){
  final String result = ((String) a).substring(1);
}
if (a is String) {
  val result = a.substring(1)
}

Nguồn.

Nguyễn Linh

Chia sẻ để cùng tiến bộ...