Use Kotlin for Android Development 1
Kotlin Basics for Android
1
Kotlin Language Fundamentals
1
Kotlin is the official language for Android development. This lesson covers the essential syntax, null safety features, and modern language constructs that will make your Android development experience smooth and productive.
Installation & Setup
1
# Create a new Android project with Kotlin support
flutter create my-android-app --org com.example --language kotlinCore Concepts
1
Variables and Types
1
// Type inference
val name = "Nyxora"
val age: Int = 30
// Explicit type declaration
val pi: Double = 3.14159
// Nullable types
var nullableString: String? = "Hello"
nullableString = null
// Non-nullable with safe call
val nonNullableString: String = "World"
val length = nonNullableString.length // Safe call operator (?.)Null Safety
1
// Safe calls
val userInput: String? = readLine()
val length = userInput?.length ?: 0 // Elvis operator for default value
// Non-null assertion
val nonNullString = userInput!! // ! operator (use with caution)
// String templates
val greeting = "Hello, $name!" // String interpolation
val template = "${age} years old"Data Classes
1
// Data class for model objects
data class User(
val id: Int,
val name: String,
val email: String
)
// Component destructuring
val (id, name, email) = userSealed Classes
1
// Sealed class for state management
sealed class AuthState {
data class LoggedIn(val user: User) : AuthState()
data class LoggedOut : AuthState()
object Unauthenticated : AuthState()
}
// Usage
when (authState) {
is AuthState.LoggedIn -> showDashboard()
is AuthState.LoggedOut -> showLogin()
AuthState.Unauthenticated -> showLogin()
}Coroutines
1
// Basic coroutine usage
import kotlinx.coroutines.*
// Launch in a coroutine
fun main() = runBlocking {
launch {
delay(1000)
println("Coroutine executed")
}
println("Main thread continues")
}Flows
1
// Cold streams with Flow
import kotlinx.coroutines.flow.*
fun numbers(): Flow<Int> = flow {
for (i in 1..5) {
delay(500)
emit(i)
}
}
// Collect flow
lifecycleScope.launch {
numbers().collect { value ->
println("Collected: $value")
}
}Practice Exercises
1
- Create a data class for a
Productwith fields:id,name,price, andinStock - Implement a function that takes a list of integers and returns the sum using a flow
- Create a sealed class for a
ConnectionStatewithConnecting,Connected, andDisconnectedstates - Write a coroutine that simulates a network request with delay and emits progress updates
Resources
1