Home > Java > javaTutorial > Kotlin for Java Developers (Part 1)

Kotlin for Java Developers (Part 1)

Mary-Kate Olsen
Release: 2025-01-27 16:04:17
Original
883 people have browsed it

Kotlin for Java Developers (Part 1)

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:

    Use the data class
  • Using empty safety
  • Under the default circumstances, non -muttering
  • Use the data class
  • This theme may soon disappear, because more and more Java developers also have experience of using records. Nevertheless, there are still some differences between the Java record and the Kotlin data class.

java method:

or as a record:

Kotlin method:
<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>
Copy after login
Copy after login
Copy after login

<code class="language-java">public record Person(
    String name,
    int age
) {
}</code>
Copy after login
Copy after login
Copy after login
You may need to understand some differences between the Java record and the Kotlin data class.

Java records and KOTLIN data categories are unchanged data carriers.

<code class="language-kotlin">data class Person(val name: String, var age: Int)</code>
Copy after login
Copy after login
Copy after login
In Java, the field is hidden in Final, which cannot be modified after the structure. In Kotlin, you can choose whether the field is variable by using Val or VAR.

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.
  • In Kotlin, you can also cover Equals, HashCode, and Tostring methods, which is impossible in Java.
  • Kotlin provides a COPY method with land, which is not available in Java.
  • Some examples:
  • Copy objects in Java

Kotlin:

or decomposed a statement in Java:

<code class="language-java">Person p2 = new Person(p1.getName(), p1.getAge());</code>
Copy after login
Copy after login
Copy after login
Kotlin:

<code class="language-kotlin">val p2 = p1.copy(age = 42)</code>
Copy after login
Copy after login
Copy after login
Reference

Kotlin data class
<code class="language-java">String name = p1.getName();
int age = p1.getAge();</code>
Copy after login
Copy after login
Copy after login

Baeldung: Kotlin data class

<code class="language-kotlin">val (name, age) = p1
println(name) // "John"
println(age) // 42</code>
Copy after login
Copy after login

Using empty safety
    In my opinion, air safety in Kotlin is one of the most powerful functions. This is a function that changes the rules of the game, which can save you a lot of time and trouble. In Kotlin, air safety is introverted in the type system, which makes it easier to avoid runtime errors related to air.
  • 1. Can be empty type
  • In Kotlin, the empty type is explicitly declared. This means that you can have a variable that might save the empty value, but you must be explicitly specified in the statement.

Non -empty type (default)

By default, all the types in Kotlin are indispensable, which means that the variable cannot save the empty value.

Can empty type

To declare a variable that can save the empty value, you must use the operator.

2. Security call

A 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>
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login
The

?.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.

3. Elvis operator (?:)

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>
Copy after login
Copy after login
Copy after login

4. !! operator (non-null assertion)

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>
Copy after login
Copy after login
Copy after login

Tips: Use of this !! operator is deprecated as it defeats the purpose of null safety.

5. Nullability in function parameters

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>
Copy after login
Copy after login
Copy after login

6. Safe conversion (as? operator)

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>
Copy after login
Copy after login
Copy after login

7. Null safety in lambda expressions

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>
Copy after login
Copy after login
Copy after login

8. Use let function

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>
Copy after login
Copy after login

9. Best Practices

  • Avoid using the !! operator
  • Safely handle nullable types and provide default values ​​using safe calls and the Elvis operator
  • Use nullable types only when necessary

Reference:

  • Kotlin Null Safety

Immutability by default

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.

1. Variables (val) that are immutable by default

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:

  • A val variable in Kotlin is actually read-only - the value assigned to it cannot be changed after initialization.
  • However, if the value is an object, the properties of the object can still be modified, unless the properties themselves are declared as val.

Example:

<code class="language-kotlin">val name: String = "John" // 不可空
name = null // 编译错误!</code>
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

Tips: Kotlin encourages using val instead of var whenever possible to ensure immutability.

2. Immutable collection

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

Difference from Java: In Java, collections (such as ArrayList) are mutable by default, which means elements can be modified freely.

3. Immutable data class

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>
Copy after login
Copy after login
Copy after login
<code class="language-kotlin">val p2 = p1.copy(age = 42)</code>
Copy after login
Copy after login
Copy after login

4. Immutability in sealed classes

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>
Copy after login
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template