Kotlin basic syntax compared to Java

· Tech· Java
Kotlin

Kotlin is a language that runs on Java's virtual machine, JVM. The Kotlin compiler converts byte code that the JVM can understand and executes it in the same format as a Java class file. It is a language with excellent compatibility with Java and guarantees similar syntax and library interoperability. I wrote basic grammar by comparing Kotlin and Java code. (excluding the same parts as Java)

Function - fun

Unlike Java, Kotlin has a simple function declaration with ``funand the output method is also simple. There is no;in each code. (It's starting to feel like a mix of Python and Java.) The part that felt most different here was the variable part. As can be seen in the code below, in the case of <span style="background-color:#fff5b1">Kotlin, the variable name is written first by </span> and then by type after:. In versions prior to Kotlin 1.3, Arrays``` was required as a parameter. For newer versions, the main function doesn't need any parameters.

// kotlin main function
fun main(args: Array<String>) {
println(args.contentToString())
}
//java main function
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
}

Kotlin displays the return type last, but it is a type that can be inferred, but the ``Unit``` return type can be omitted.

// kotlin function
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum(a: Int, b: Int) = a + b
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
// java function
public int sum(int a, int b){
return a + b;
}

[Infix notation] In Korean, it is called infix notation. That means putting a specific expression between two values. Here, to of Pair was used, but using the Pair constructor also produces the same result.

val pair = "Ferrari" to "Katrina"
println(pair)

When combining three variables, you can initialize the variables using Triple. Each variable can be accessed as first, second, and third.

val (a, b, c) = Triple(2, "x", listOf(null))
println(a) // 2
println(b) // x
println(c) // [null]

Infix function is expressed as infix fun, and has the following format: infix fun dispatcher.function name (receiver): return type { implementation section }. dispatcher is the object that comes before Infix, and receiver is the object that comes after Infix.

infix fun Int.times(str: String) = str.repeat(this)
println(2 times "Bye ")

Variables - val, var, const

In Kotlin, the variable type is inferred without having to write it down, so it can be omitted. var is a variable that can be reassigned, and val is used when the value of the data to be declared does not change. const refers to a variable with a fixed value, like a constant with ``static final``` in Java.

// kotlin variable
var x: Int = 5
var x = 5 // `Int` type inferred
val y = 5 // constant
// java variable
int x = 5;
final int y = 5;

Difference between val and const val val```` is a constant that has incomplete invariance and is determined at <span style="background-color:#fff5b1">runtime. If you think about a val variable that receives a function, the value of the val variable can change depending on the parameter values ​​of the function. On the other hand, const valis a constant that is determined at <span style="background-color:#fff5b1">compilation time and generally always has the same value regardless of the state of the function or class. And variable names are expressed usingcapital lettersand_. It cannot be used as a local variable or class attribute within a function, so it must be used together with companion object``` as follows. Constants determined at runtime and constants determined at compile time Constants determined at run time are dynamically allocated to memory during execution, and constants determined at compile time are allocated to the data area of the compiled code (= static allocation). In other words, constants determined at compile time are allocated to the data area, so their values cannot be changed. Therefore, when using constants related to security, it is appropriate to use constants that are determined at runtime.

class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}

string template

This part feels somewhat similar to the syntax of ``Spring Thymeleaf``` in that it uses a grammar that converts variables within a string. Why was s1 set to a constant? I used the code provided by Doc, but why did I set s1 to a constant? I checked to see if the value would change if I reset a. However, we confirmed that the value a in the Java String type did not change as if it did not change. Nonetheless, specifying constants in code provides convenience in maintainability and readability by indicating immutability.

// kotlin string template
var a = 1
val s1 = "a is $a"
a = 2
val s2 = "${s1.replace("is", "was")}, but now is $a"
//java string template
int a = 1;
String s1 = "a is " + a;
a = 2;
String s2 = s1 + ", but now is "+ a;

Conditional statement

In Kotlin, it can be expressed succinctly by assigning the value of a conditional statement, as shown in the code below.

// kotlin conditional statement
fun maxOf(a: Int, b: Int) = if (a > b) a else b
// java conditional statement
public int maxOf(int a, int b){
return a>b? a:b;
}

There is a ````when expression that is similar to Java's ``switch statement, and the expression method is almost similar. This code can also be written in an assignment format like the ``if conditional``` above.

fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}

loop

In Java, it was inconvenient because there was no separate way to provide indices in for loops and enhanced for loops, but in Kotlin, .indices provides a valid index range 0..list.lastIndex. In addition, it is provided as a collection with forEachIndex. (The while statement was omitted because Java and Kotlin are almost similar.)

// kotlin loop
val items = listOf("apple", "banana", "kiwifruit")
// Method 1
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
// Method 2
list.forEachIndexed{index, element ->
println("item at ${index} is ${element}")
}
// java loop
List<String> list = List.of("apple", "banana", "kiwifruit");
for(int i=0; i<list.length; i++){
System.out.println("item at " + i + " is " + list.get(i););
}

Range, there is downTo, which is used to repeat the range by jumping the value like step or to repeat by decreasing the number.

for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}

Collections

Kotlin also provides collections, and the representative example is ``Lambda expression. Unlike Java, it uses { }```.

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }

Null-Safety

This is the feature that developers who moved from Java to Kotlin say is the most convenient. Kotlin provides the Null-Safety feature to prevent risks caused by null references. To use null in Kotlin, use var b: String? = "abc", you must add ? after the type to allow it. If you try to use another method with a nullable variable, a compiler error will occur and indicate the possibility of nullability. In this case, you can resolve it with Safe calls. In the previous example, to find the length of the variable b with a null value as a nullable variable, an expression such as b?.length is possible. If you use Safe calls like this, if the variable is null, its value will also return null. If you additionally use let here, the method inside { } will be executed only if it is not null. In other words, even if there is a null in the list in the code below, only Kotlin is output, not null. If it were Java, it would have been output using conditional statements, but you can clearly see that the code has become simpler.

val listWithNulls: List<String?> = listOf("Kotlin", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints Kotlin and ignores null
}

Type check

In Kotlin, type is checked using is. Performs the same function as ``instanceof``` in Java.

if (obj !is String) return null

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164