ANDROID_LIVE Telegram 1051
When и Guard Conditions
#kotlin

С релизом Kotlin 2.1.0 появился апдейт для when — guard conditions. Эта новая фича улучшает читаемость кода, делая его более наглядным.
Давайте рассмотрим на примере, что она делает.

Предположим, есть базовый класс для получения ответа от сервера:

sealed interface HttpResult {
data class Success(val response: String) : HttpResult
data class Failed(val statusCode: Int) : HttpResult
}


Если включить Guard Conditions, то проверка в when специальных юзкейсов будет выглядеть так:

when (response) {
is HttpResult.Success -> println("Success")
is HttpResult.Failed if response.statusCode == 503 -> println("Maintenance")
is HttpResult.Failed -> println("Failed with code ${response.statusCode}")
}


Как мы видим, одну ошибку от бэка мы обработали без добавления if внутри условия:

when (response) {
is HttpResult.Success -> println("Success")
is HttpResult.Failed -> {
if (response.statusCode == 503) {
println("Maintenance")
} else {
println("Failed with code ${response.statusCode}")
}
}
}


Похоже, что стало удобнее, но нужно попробовать на практике.
Чтобы включить фичу, надо убедиться, что K2 Compiler включен, а потом добавить опцию:

kotlin {
compilerOptions {
freeCompilerArgs.add("-Xwhen-guards")
}
}


Чуть больше информации можно найти тут.
13👍9👎3🤔3



tgoop.com/android_live/1051
Create:
Last Update:

When и Guard Conditions
#kotlin

С релизом Kotlin 2.1.0 появился апдейт для when — guard conditions. Эта новая фича улучшает читаемость кода, делая его более наглядным.
Давайте рассмотрим на примере, что она делает.

Предположим, есть базовый класс для получения ответа от сервера:


sealed interface HttpResult {
data class Success(val response: String) : HttpResult
data class Failed(val statusCode: Int) : HttpResult
}


Если включить Guard Conditions, то проверка в when специальных юзкейсов будет выглядеть так:

when (response) {
is HttpResult.Success -> println("Success")
is HttpResult.Failed if response.statusCode == 503 -> println("Maintenance")
is HttpResult.Failed -> println("Failed with code ${response.statusCode}")
}


Как мы видим, одну ошибку от бэка мы обработали без добавления if внутри условия:

when (response) {
is HttpResult.Success -> println("Success")
is HttpResult.Failed -> {
if (response.statusCode == 503) {
println("Maintenance")
} else {
println("Failed with code ${response.statusCode}")
}
}
}


Похоже, что стало удобнее, но нужно попробовать на практике.
Чтобы включить фичу, надо убедиться, что K2 Compiler включен, а потом добавить опцию:

kotlin {
compilerOptions {
freeCompilerArgs.add("-Xwhen-guards")
}
}


Чуть больше информации можно найти тут.

BY Android Live 🤖


Share with your friend now:
tgoop.com/android_live/1051

View MORE
Open in Telegram


Telegram News

Date: |

A few years ago, you had to use a special bot to run a poll on Telegram. Now you can easily do that yourself in two clicks. Hit the Menu icon and select “Create Poll.” Write your question and add up to 10 options. Running polls is a powerful strategy for getting feedback from your audience. If you’re considering the possibility of modifying your channel in any way, be sure to ask your subscribers’ opinions first. “[The defendant] could not shift his criminal liability,” Hui said. In the next window, choose the type of your channel. If you want your channel to be public, you need to develop a link for it. In the screenshot below, it’s ”/catmarketing.” If your selected link is unavailable, you’ll need to suggest another option. Add the logo from your device. Adjust the visible area of your image. Congratulations! Now your Telegram channel has a face Click “Save”.! As five out of seven counts were serious, Hui sentenced Ng to six years and six months in jail.
from us


Telegram Android Live 🤖
FROM American