Java occupies a dominant position in the programming language, so I have seen the same mistakes when using Java developers when using Kotlin. Don't get me wrong. This is not to say that these are bugs, but when developers are accustomed to developing in Java, tend to produce "code odors" in Kotlin, and do not use Kotlin's function.
This article will let you know the odor odor I often see and how to realize them ideal in the "Kotlin".
The first part of this series will cover:
or as a record:
<code class="language-java">public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } // Getters, setters, ... }</code>
<code class="language-java">public record Person( String name, int age ) { }</code>
Java records and KOTLIN data categories are unchanged data carriers.
<code class="language-kotlin">data class Person(val name: String, var age: Int)</code>
Another difference is that the record type in Java is Final and Sealed, which means that they cannot be extended, and in Kotlin, you can expand the data class.
Kotlin:
or decomposed a statement in Java:
<code class="language-java">Person p2 = new Person(p1.getName(), p1.getAge());</code>
<code class="language-kotlin">val p2 = p1.copy(age = 42)</code>
Kotlin data class
<code class="language-java">String name = p1.getName(); int age = p1.getAge();</code>
Baeldung: Kotlin data class
<code class="language-kotlin">val (name, age) = p1 println(name) // "John" println(age) // 42</code>
By default, all the types in Kotlin are indispensable, which means that the variable cannot save the empty value.
To declare a variable that can save the empty value, you must use the operator.
2. Security callA powerful function is the safe calling operator?. It allows you to steam safely methods or access attributes without throwing NullPointerexception.
<code class="language-kotlin">val name: String = "John" // 不可空 name = null // 编译错误!</code>
Example
<code class="language-java">public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } // Getters, setters, ... }</code>
?.operator checks if the object is empty, if so it returns null immediately, otherwise it continues to call methods or access properties. If the object is empty, the entire expression evaluates to null.
Elvis operator?: is the abbreviation for returning the default value if the expression on the left side of the operator is empty.
<code class="language-java">public record Person( String name, int age ) { }</code>
You can use the !! operator to tell the compiler that the value is not null. If the value is null, it will throw NullPointerException.
<code class="language-kotlin">data class Person(val name: String, var age: Int)</code>
Tips: Use of this !! operator is deprecated as it defeats the purpose of null safety.
When defining a function, you can specify whether the parameters can be null. In this case the caller must handle it.
<code class="language-java">Person p2 = new Person(p1.getName(), p1.getAge());</code>
There is a safe conversion operator as?, which returns null if conversion is not possible.
<code class="language-kotlin">val p2 = p1.copy(age = 42)</code>
You can also use null-safety features in lambda expressions and higher-order functions:
<code class="language-java">String name = p1.getName(); int age = p1.getAge();</code>
The let function is a scoped function that allows you to execute a block of code on a non-null object. It is commonly used to execute code on nullable objects in a safe manner.
Example and default value:
<code class="language-kotlin">val (name, age) = p1 println(name) // "John" println(age) // 42</code>
Kotlin strongly encourages functional programming style! For functional programming style, immutability plays a crucial role in avoiding errors, especially in multi-threaded applications.
I will probably write a separate article about functional programming in Kotlin or Java now, but for now let’s focus on immutability.
Kotlin essentially prefers immutable objects to mutable objects. This results in simpler and more predictable code, especially in concurrent environments.
In Kotlin, variables declared using the val keyword are immutable by default. This is very close to declaring final variables in Java, but with some key differences:
Example:
<code class="language-kotlin">val name: String = "John" // 不可空 name = null // 编译错误!</code>
Difference from Java: In Java, we use the final keyword to ensure that the variable cannot be reassigned, but the object it points to can still be mutable. The key difference in Kotlin is that immutability extends to variables by default, which encourages a more predictable and secure design for the entire application.
Variable variable example: Using the var keyword in Kotlin allows you to reassign a variable.
<code class="language-java">public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } // Getters, setters, ... }</code>
Tips: Kotlin encourages using val instead of var whenever possible to ensure immutability.
Immutable collections are also encouraged by default. Immutable collections prevent any modification after creation, for example, if you create a List using listOf(), you cannot change it, no elements can be added, removed, or changed.
<code class="language-java">public record Person( String name, int age ) { }</code>
If you need to modify the collection, you can use mutableListOf() or other mutable collection types.
<code class="language-kotlin">data class Person(val name: String, var age: Int)</code>
Difference from Java: In Java, collections (such as ArrayList) are mutable by default, which means elements can be modified freely.
Kotlin’s data classes are immutable by default. When defining a data class, properties are usually declared as val, making the class immutable. This makes classes ideal for value objects, especially when dealing with APIs, database records, or any other scenario where the object's state should not change after creation.
<code class="language-java">Person p2 = new Person(p1.getName(), p1.getAge());</code>
<code class="language-kotlin">val p2 = p1.copy(age = 42)</code>
Kotlin’s sealed classes can also be immutable, and they work well with the immutable data model. Sealed classes are often used to represent restricted class hierarchies, such as state or responses, and their immutability ensures that the state or results cannot change unexpectedly.
<code class="language-java">String name = p1.getName(); int age = p1.getAge();</code>
The above is the detailed content of Kotlin for Java Developers (Part 1). For more information, please follow other related articles on the PHP Chinese website!