Home Java javaTutorial Comparison details of the use of Optional in Java8 and nullable types in Kotlin

Comparison details of the use of Optional in Java8 and nullable types in Kotlin

Sep 19, 2017 am 10:15 AM
java8 kotlin optional

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();
 }
}
Copy after login

Run output:


3
0
Copy after login

However, such code is still not so elegant.

In this regard, Groovy provides a safe property/method access operator?.


user?.getUsername()?.toUpperCase();
Copy after login

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

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();
Copy after login

This stuff is the most common Elvis operator in Kotlin:


s?.length ?: 0
Copy after login

In contrast, what reasons are there to continue using Java 8’s Optional?

Star symbols in Kotlin


??????????????????????????????????????
?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: ?: 
?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?. ?.
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Some tips for developing Android applications using Vue.js and Kotlin language Some tips for developing Android applications using Vue.js and Kotlin language Jul 31, 2023 pm 02:17 PM

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

How to calculate date one year ago or one year later in Java 8? How to calculate date one year ago or one year later in Java 8? Apr 26, 2023 am 09:22 AM

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

How to install the Kotlin programming language 12 on Debian How to install the Kotlin programming language 12 on Debian Feb 20, 2024 am 09:42 AM

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 How to use Redis and Kotlin to develop asynchronous task queue functions Sep 21, 2023 am 10:58 AM

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?

What is the difference between Java functions and Kotlin language functions? What is the difference between Java functions and Kotlin language functions? Apr 24, 2024 am 08:24 AM

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 date one week later using Java 8? How to calculate date one week later using Java 8? Apr 21, 2023 pm 11:01 PM

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[

What are the commonly used Optional methods in Java? What are the commonly used Optional methods in Java? May 09, 2023 am 11:34 AM

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 develop distributed queue functions using Redis and Kotlin How to develop distributed queue functions using Redis and Kotlin Sep 20, 2023 am 10:09 AM

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

See all articles