


Comparison details of the use of Optional in Java8 and nullable types in Kotlin
This article mainly introduces to you the comparison of the use of Optional types in Java8 and nullable types in Kotlin. The article introduces it to you in great detail through example code, which has certain reference learning value for everyone's study or work. Friends who need it, please follow the editor to learn together.
This article mainly introduces to you the relevant content about the use of Optional types in Java8 and nullable types in Kotlin. It is shared for your reference and study. I won’t say much below, let’s take a look at the detailed introduction:
In Java 8, we can use the Optional type to express nullable types.
package com.easy.kotlin; import java.util.Optional; import static java.lang.System.out; /** * Optional.ofNullable - 允许传递为 null 参数 * Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException * Optional<String> b = Optional.of(s); */ public class Java8OptionalDemo { public static void main(String[] args) { out.println(strLength(Optional.of("abc"))); out.println(strLength(Optional.ofNullable(null))); } static Integer strLength(Optional<String> s) { return s.orElse("").length(); } }
Run output:
3 0
However, such code is still not so elegant.
In this regard, Groovy provides a safe property/method access operator?.
user?.getUsername()?.toUpperCase();
Swift also has similar syntax, which only works on Optional on the type.
Nullable types in Kotlin
The above Java 8 example is simpler and more elegant when written in Kotlin:
package com.easy.kotlin fun main(args: Array<String>) { println(strLength(null)) println(strLength("abc")) } fun strLength(s: String?): Int { return s?.length ?: 0 }
Among them, we use String? which also expresses the meaning of Optional<String>
. In comparison, which one is simpler?
Clear at a glance.
There is also orElse provided by Java 8 Optional
s.orElse("").length();
This stuff is the most common Elvis operator in Kotlin:
s?.length ?: 0
In contrast, what reasons are there to continue using Java 8’s Optional?
Star symbols in Kotlin
?????????????????????????????????????? ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?.
The above is the detailed content of Comparison details of the use of Optional in Java8 and nullable types in Kotlin. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Some tips for developing Android applications using Vue.js and Kotlin language. With the popularity of mobile applications and the continuous growth of user needs, the development of Android applications has attracted more and more attention from developers. When developing Android apps, choosing the right technology stack is crucial. In recent years, Vue.js and Kotlin languages have gradually become popular choices for Android application development. This article will introduce some techniques for developing Android applications using Vue.js and Kotlin language, and give corresponding code examples. 1. Set up the development environment at the beginning

Java8 calculates the date one year ago or one year later using the minus() method to calculate the date one year ago packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args ){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

Kotlin is a statically typed programming language that has attracted huge attention in the field of software development. Its concise and easy-to-understand syntax, good compatibility with Java, and rich tool support provide developers with many advantages, so many developers choose Kotlin as their preferred language. Install Kotlin Programming Language 12Bookworm on Debian Step 1. Start by updating existing system packages. Open a terminal and enter the following commands: sudoaptupdatesudoaptupgrade These commands will get a list of available updates and upgrade current packages, ensuring your system is up to date. Step 2. Install Java. Kotlin in the Java Virtual Machine (J

How to use Redis and Kotlin to develop asynchronous task queue functions Introduction: With the development of the Internet, the processing of asynchronous tasks has become more and more important. During the development process, we often encounter some time-consuming tasks, such as sending emails, processing big data, etc. In order to improve the performance and scalability of the system, we can use asynchronous task queues to process these tasks. This article will introduce how to use Redis and Kotlin to develop a simple asynchronous task queue, and provide specific code examples. 1. What is an asynchronous task?

The difference between Java and Kotlin functions: Syntax: Java functions need to specify parameter types and names, while Kotlin can omit the type and use lambda expressions; Parameters: Kotlin can omit parameter types using more concise syntax; Return value: Kotlin can omit the return value Type, the default is Unit; extension function: Kotlin can add new functions to existing classes, while Java needs to implement similar functions through inheritance; instance method call: Kotlin can omit the object name and use a more concise syntax.

How to calculate the date one week later in Java8 This example will calculate the date one week later. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks, and months. The ChronoUnit class declares these time units. Since LocalDate is also an immutable type, you must use variables to assign values after returning. packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

Preface Optional in Java is a container object, which can contain a non-null value or be empty. Its main purpose is to avoid null pointer exceptions when writing code. The complete usage of Optional in java8 is as follows: 1. Create an Optional object. You can create an Optional object containing a non-null value through the of() method, for example: Optionaloptional=Optional.of("value"); It can also be created through the ofNullable() method. An Optional object containing a possibly null value, for example: Optionaloptional=Optiona

How to use Redis and Kotlin to develop distributed queue functions Introduction: With the rapid development of the Internet, distributed systems have attracted more and more attention. Distributed queue is one of the important components of distributed system, which can realize asynchronous processing and decoupling of messages. This article will introduce how to develop a simple distributed queue using Redis and Kotlin, and provide specific code examples. 1. Overview Distributed queues can publish and consume messages and ensure that messages are not lost. In a distributed system, the publishing and consumption of messages
