Kotlin Null Safety
БесплатноБез исполняемых скриптовНе проверенUse when kotlin's null safety system including nullable types, safe calls, Elvis operator, smart casts, and patterns for eliminating NullPointerExceptions…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Kotlin Null Safety
Introduction
Kotlin's null safety system eliminates NullPointerExceptions at compile time by distinguishing between nullable and non-nullable types in the type system. This approach makes null handling explicit and forces developers to consciously handle potential null values.
Unlike Java where any reference can be null, Kotlin requires explicit
declaration of nullability with the ? operator. The compiler enforces null
checks before dereferencing nullable values, preventing the vast majority of
null-related crashes that plague Java applications.
This skill covers nullable types, safe call operators, smart casts, nullability in generic types, and patterns for designing null-safe APIs while maintaining code clarity.
Nullable Types
Nullable types explicitly indicate that a variable or property can hold null, while non-nullable types provide compile-time guarantees of non-null values.
// Non-nullable types
var name: String = "Alice"
// name = null // Compilation error
// Nullable types
var nullableName: String? = "Bob"
nullableName = null // OK
// Function parameters
fun greet(name: String) {
println("Hello, $name")
}
fun greetNullable(name: String?) {
if (name != null) {
println("Hello, $name")
} else {
println("Hello, guest")
}
}
// greet(null) // Compilation error
greetNullable(null) // OK
// Nullable return types
fun findUser(id: Int): User? {
return if (id > 0) User(id, "Alice") else null
}
data class User(val id: Int, val name: String)
// Nullable properties
class Person(
val name: String,
val email: String?,
var phoneNumber: String?
)
// Collections with nullable elements
val nullableList: List<String?> = listOf("A", null, "B")
val listOfNullable: List<String>? = null
// Platform types from Java (String!)
// Treated as nullable for safety in Kotlin
// Nullable this
class Service {
fun process() {
val self: Service? = this
self?.validate()
}
fun validate() {}
}
The ? suffix makes a type nullable. Non-nullable types cannot be assigned null
without explicit nullability declaration, preventing accidental null references.
Safe Call Operator
The safe call operator ?. safely accesses properties and methods on nullable
references, returning null if the receiver is null instead of throwing NPE.
// Basic safe calls
val name: String? = "Alice"
val length: Int? = name?.length
val nullName: String? = null
val nullLength: Int? = nullName?.length // Returns null
// Chaining safe calls
data class Address(val street: String?, val city: String?)
data class Company(val address: Address?)
data class Employee(val company: Company?)
val employee: Employee? = Employee(Company(Address("Main St", "NYC")))
val city: String? = employee?.company?.address?.city
println(city) // "NYC"
val nullEmployee: Employee? = null
val nullCity: String? = nullEmployee?.company?.address?.city
println(nullCity) // null
// Safe calls with methods
fun processUser(user: User?) {
user?.let { u ->
println("Processing ${u.name}")
}
}
// Safe calls with extension functions
fun String?.orDefault(default: String): String {
return this ?: default
}
val result = nullName?.orDefault("Unknown")
// Safe calls in expressions
class Profile(val bio: String?)
fun displayBio(profile: Profile?) {
val bioLength = profile?.bio?.length ?: 0
println("Bio length: $bioLength")
}
// Safe calls with mutable properties
class Container {
var value: String? = null
fun updateValue() {
value?.let { current ->
value = current.uppercase()
}
}
}
Safe call chains short-circuit at the first null, making deeply nested optional access clean and safe without multiple null checks.
Elvis Operator and Null Coalescing
The Elvis operator ?: provides default values for null expressions, enabling
concise fallback logic without verbose if-else statements.
// Basic Elvis operator
val name: String? = null
val displayName = name ?: "Guest"
println(displayName) // "Guest"
// Elvis with safe calls
fun getUserCity(employee: Employee?): String {
return employee?.company?.address?.city ?: "Unknown"
}
// Elvis with expressions
fun calculateTotal(subtotal: Double?, taxRate: Double?): Double {
val sub = subtotal ?: 0.0
val tax = taxRate ?: 0.15
return sub * (1 + tax)
}
// Elvis with return/throw
fun requireName(name: String?): String {
return name ?: throw IllegalArgumentException("Name required")
}
fun processUser(user: User?) {
val u = user ?: return
println("Processing ${u.name}")
}
// Chaining Elvis operators
fun findValidValue(
primary: String?,
secondary: String?,
tertiary: String?
): String {
return primary ?: secondary ?: tertiary ?: "default"
}
// Elvis with nullable properties
class Config {
var timeout: Int? = null
fun getTimeout(): Int {
return timeout ?: 30000
}
}
//
Установить Kotlin Null Safety в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Kotlin Null Safety?
Use when kotlin's null safety system including nullable types, safe calls, Elvis operator, smart casts, and patterns for eliminating NullPointerExceptions while maintaining code expressiveness and clarity.
Как установить скилл Kotlin Null Safety?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Kotlin Null Safety запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic