Kotlin vs Java
public static void main(final String[] args) {
System.out.println("Hello world!");
}
fun main() {
println("Hello world!")
}
fun main(args: Array<String>) {
println("Hello World!")
}
var x; // compile-time error
final var xx; // compile-time error
final var y = 1;
val x: Int // compile-time error
val y // compile-time error
val z = 2
int w;
int z = 2;
z = 3;
w = 1;
var q // compile-time error
var w: Int // compile-time error
var z = 2
final String name = null;
String lastName;
lastName = null;
val name: String? = null
var lastName: String?
lastName = null
var firstName: String
firstName = null // Compilation error!!
final Integer length =
bob != null
&& bob.department != null
&& bob.department.text != null
? bob.department.text.length()
: null;
val length = bob?.department?.text?.length
final var result = Optional.ofNullable(nullableVariable)
.flatMap(v -> Optional.ofNullable(v.someNullableMethodCall()))
.orElseGet(() -> fallbackIfNullMethodCall())
val result = nullableVariable?.someNullableMethodCall() ?: fallbackIfNullMethodCall()
final var name = "John";
final var lastName = "Smith";
final var text = "My name is: " + name + " " + lastName;
final var 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)}"
final var text = "First Line\n" +
"Second Line\n" +
"Third Line";
val text = """
|First Line
|Second Line
|Third Line
""".trimMargin()
final var text = x > 5 ? "x > 5" : "x <= 5";
val text = if (x > 5) "x > 5" else "x <= 5"
var size = 1;
var numbers = new int[size];
numbers[0] = 1;
var bigNumbers = new long[size];
var strings = new String[size];
val size = 1
val numbers = IntArray(size)
numbers[0] = 1
val bigNumbers = LongArray(size)
val strings = Array(size) { String() }
var file = new File("contents.txt");
try {
var fileReader = new FileReader(file);
try (var bufferedReader = new BufferedReader(fileReader)) {
// the bufferedReader is closed automatically
}
} catch (IOException ex) {
// handle the exception
}
File("contents.txt")
.bufferedReader()
.use {
// the bufferedReader is closed automatically
}