Kotlin if empty string

Checking if a String is Empty in Kotlin

announcement - icon

As a seasoned developer, you’re likely already familiar with Spring. But Kotlin can take your developer experience with Spring to the next level!

  • Add new functionality to existing classes with Kotlin extension functions.
  • Use Kotlin bean definition DSL.
  • Better configure your application using lateinit.
  • Use sequences and default argument values to write more expressive code.

By the end of this talk, you’ll have a deeper understanding of the advanced Kotlin techniques that are available to you as a Spring developer, and be able to use them effectively in your projects.

1. Overview

Depending on our nullability constraints and other requirements, there are a few extensions in Kotlin that can help us to determine the emptiness of a String.

In this short tutorial, we’re going to get familiar with those functions to check if a String is empty or even blank in Kotlin.

2. Empty Strings

A String is empty if its length is zero. In order to determine if a non-nullable String is empty or not, we can use the isEmpty() extension function:

On the other hand, to check if a String is not empty, in addition to the negation operator, we can also use the isNotEmpty() extension function:

val nonEmpty = "42" assertTrue

In addition to Strings, these extensions are applicable to all sorts of CharSequences such as StringBuilder:

val sb = StringBuilder() assertTrue

Here, we’re making sure the given StringBuilder is actually empty.

For nullable Strings, it’s also possible to check if the value is either null or empty using the isNullOrEmpty() function:

val nullStr: String? = null val emptyNullable: String? = "" assertTrue < nullStr.isNullOrEmpty() >assertTrue

2.1. Simplifying Conditional Logic

Sometimes we may need traditional if-else conditional branches to work around empty values:

val ipAddress = request.getHeader("X-FORWARDED-FOR") val source = if (ipAddress.isEmpty()) "default-value" else ipAddress

As of Kotlin 1.3, we can avoid this imperative style with a more functional approach using the ifEmpty()higher-order function:

val source = request.getHeader("X-FORWARDED-FOR").ifEmpty

As we see, this is much simpler and more concise!

3. Blank Strings

A String is blank when either its length is zero or it contains only whitespace characters. In order to check if a non-nullable String is blank, we can use the isBlank() function:

val blank = " " val empty = "" val notBlank = " 42" assertTrue < empty.isBlank() >assertTrue < blank.isBlank() >assertTrue

Similar to isNotEmpty(), the isNotBlank() function serves as a more readable alternative for the negation operator.

Again, quite similar to isNullOrEmpty(), there’s an isNullOrBlank() function:

val nullStr: String? = null val blankNullable: String? = " " assertTrue < nullStr.isNullOrBlank() >assertTrue

This function returns true if the value is either null or blank. In addition to all these similarities, the ifBlank() higher-order function helps us to provide defaults for blank values.

4. Conclusion

In this tutorial, we got familiar with a few functions that can help us to check if a string is empty or blank.

As usual, all the examples are available over on GitHub.

Источник

Проверьте, является ли строка пустой или нулевой в Kotlin

В этой статье рассматриваются различные способы проверки того, является ли строка пустой или нулевой в Kotlin.

1. Использование isNullOrEmpty() функция

Стандартный подход в Kotlin для проверки null или пустая строка с isNullOrEmpty() функция.

2. Использование isEmpty() функция

В качестве альтернативы вы можете использовать isEmpty() функция для проверки пустой строки в Kotlin. Чтобы также проверить значение null, ему должна предшествовать проверка null.

Вместо того, чтобы явно проверять, является ли строка нулевой, вы можете использовать оператор безопасного вызова, записанный как ?. вместе с оператором Элвиса, записанным как ?: :

Чтобы проверить обратное, т. е. что строка не пуста, используйте функцию isNotEmpty() функция.

3. Использование length имущество

The isEmpty() функция внутренне проверяет length свойство строки. Строка пуста, если ее длина равна 0. Вы можете напрямую вызвать length свойство, как показано ниже:

4. Использование == оператор

Другое решение — выполнить проверку на равенство с пустой строкой. Рассмотрим следующий код, который проверяет, что строка точно равна пустой строке. «» .

5. Использование isNullOrBlank() функция

Вы можете использовать isNullOrBlank() функция для дополнительной проверки пробельных символов вместе с null или пустой.

Это все, что касается определения того, является ли строка пустой или нулевой в Kotlin.

Средний рейтинг 4.45 /5. Подсчет голосов: 29

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

How to Check if String is Empty in Kotlin?

In this tutorial, you shall learn how to check if given string is empty in Kotlin, using String.isEmpty() function, with examples.

Kotlin – Check if String is Empty

To check if string is empty in Kotlin, call isEmpty() method on this string. The method returns a boolean value of true, if the string is empty, or false if the string is not empty.

Syntax

The syntax of isEmpty() method is

fun CharSequence.isEmpty(): Boolean

Since isEmpty() returns a boolean value, we can use this as a condition in Kotlin If-Else statement.

Examples

In the following example, we take a string in str and check if this string is empty or not using isEmpty().

Now, let us take a non-empty string in str , and find the output.

Conclusion

In this Kotlin Tutorial, we learned how to check if given string is empty or not using String.isEmpty(), with examples.

  • How to Check if String Ends with Specified Character in Kotlin?
  • How to Check if String Ends with Specified String in Kotlin?
  • How to Check if String Starts with Specified Character in Kotlin?
  • How to Check if String Starts with Specified String Value in Kotlin?
  • How to Check if Two Strings are Equal in Kotlin?
  • How to Compare Strings in Kotlin?
  • How to Compare Strings in Kotlin?
  • How to Create an Empty String in Kotlin?
  • How to Filter Characters of String in Kotlin?
  • How to Filter List of Strings based on Length in Kotlin?
  • How to Filter only Non-Empty Strings of Kotlin List?
  • How to Filter only Strings from a Kotlin List?
  • How to Get Character at Specific Index of String in Kotlin?
  • How to Initialize String in Kotlin?
  • How to Iterate over Each Character in the String in Kotlin?
  • How to Remove First N Characters from String in Kotlin?
  • How to Remove Last N Characters from String in Kotlin?
  • How to check if a String contains Specified String in Kotlin?
  • How to create a Set of Strings in Kotlin?
  • How to define a List of Strings in Kotlin?
  • How to define a String Constant in Kotlin?
  • How to get Substring of a String in Kotlin?
  • Kotlin String Concatenation
  • Kotlin String Length
  • Kotlin String Operations
  • Kotlin String.capitalize() – Capitalize First Character
  • Kotlin – Split String to Lines – String.lines() function
  • Kotlin – Split String – Examples
  • Kotlin – String Replace – Examples
  • Kotlin – String to Integer – String.toInt()
  • [Solved] Kotlin Error: Null can not be a value of a non-null type String

Источник

Читайте также:  Counter Online Users and Visitors
Оцените статью