Kotlin Cursor Rules: Android Development Best Practices
Cursor rules for Kotlin and Android enforcing Jetpack Compose, coroutines, and clean architecture. Helps AI generate secure, production-ready code with context.
Overview
Professional cursor rules for Kotlin Android development that emphasize modern architecture, Jetpack Compose, and coroutine-based concurrency. These rules help AI assistants generate clean, testable, and maintainable Kotlin code with complete project context.
Note:
Optimizes Jetpack Compose, coroutines, and Android architecture components with context-aware code generation aligned to modern best practices.
Rules Configuration
.cursor/rules/kotlin.mdc
---
description: Enforces best practices for Kotlin development, focusing on context-aware code generation, modern patterns, and maintainable architecture. Provides comprehensive guidelines for writing clean, efficient, and secure Kotlin code with proper context for Android development.
globs: **/*.{kt,kts}
---
# Kotlin Best Practices
You are an expert in Kotlin programming, Android development, Jetpack Compose, and related mobile technologies.
You understand modern Kotlin development practices, architectural patterns, and the importance of providing complete context in code generation.
### Context-Aware Code Generation
- Always provide complete class context including package declarations and imports
- Include relevant configuration files (build.gradle.kts) when generating projects
- Generate complete function signatures with proper parameters, return types, and KDoc
- Include comprehensive KDoc blocks explaining the purpose, parameters, and return values
- Provide context about the class's role in the larger system architecture
### Code Style and Structure
- Follow Kotlin coding conventions and clean code principles
- Structure code in logical packages following domain-driven design
- Implement proper separation of concerns (activities, fragments, viewmodels, repositories)
- Use modern Kotlin features (coroutines, flow, extension functions) appropriately
- Maintain consistent code formatting using ktlint or similar tools
- Use proper package structure and naming conventions
### Android Best Practices
- Use Android Jetpack components and architecture patterns
- Implement proper dependency injection with Hilt or Koin
- Configure proper navigation with Navigation Component
- Use proper lifecycle-aware components
- Implement proper error handling and logging
- Configure proper testing setup (JUnit, Espresso, Robolectric)
### Testing and Quality
- Write comprehensive unit tests with proper test context
- Include integration tests for critical paths
- Use proper mocking strategies with Mockito or MockK
- Implement UI tests with Espresso or Compose testing
- Include performance tests for critical components
- Maintain high test coverage for core business logic
### Security and Performance
- Implement proper input validation and sanitization
- Use secure authentication and token management
- Configure proper permissions handling
- Implement rate limiting and request validation
- Use proper caching strategies
- Optimize UI rendering and database operations
### UI Design
- Follow Material Design guidelines
- Implement responsive layouts for different screen sizes
- Use proper theme and styling
- Implement proper accessibility features
- Use Jetpack Compose for modern UI development
- Implement proper animations and transitions
### State Management
- Use proper state management patterns (ViewModel, StateFlow)
- Implement proper data fetching strategies
- Use proper caching mechanisms
- Handle loading and error states properly
- Implement proper optimistic updates
- Use proper state persistence when needed
### Build and Deployment
- Use Gradle for build management
- Implement proper CI/CD pipelines
- Configure proper signing and release process
- Configure proper environment variables
- Implement proper logging and monitoring
- Use proper deployment strategies
### Examples
```kotlin
/**
* UserService handles user-related operations.
* Provides methods for user management and authentication.
*/
class UserService @Inject constructor(
private val apiClient: ApiClient,
private val cache: Cache
) {
/**
* Finds a user by their email address.
*
* @param email The email address to search for
* @return Flow containing the user if found
* @throws ApiException if the request fails
*/
suspend fun findUserByEmail(email: String): Flow<User?> = flow {
try {
val cachedUser = cache.get<User>("user:$email")
if (cachedUser != null) {
emit(cachedUser)
return@flow
}
val user = apiClient.get<User>("/users?email=$email")
cache.set("user:$email", user)
emit(user)
} catch (e: Exception) {
throw ApiException("Failed to find user by email: ${e.message}")
}
}
}
/**
* Tests for UserService functionality.
*/
@RunWith(MockitoJUnitRunner::class)
class UserServiceTest {
@Mock
private lateinit var apiClient: ApiClient
@Mock
private lateinit var cache: Cache
private lateinit var service: UserService
@Before
fun setup() {
service = UserService(apiClient, cache)
}
@Test
fun `finds user by email when user exists`() = runTest {
val email = "[email protected]"
val user = User(id = 1, email = email)
whenever(apiClient.get<User>("/users?email=$email")).thenReturn(user)
val result = service.findUserByEmail(email).first()
assertNotNull(result)
assertEquals(email, result?.email)
verify(apiClient).get<User>("/users?email=$email")
}
@Test
fun `returns null when user not found`() = runTest {
val email = "[email protected]"
whenever(apiClient.get<User>("/users?email=$email")).thenReturn(null)
val result = service.findUserByEmail(email).first()
assertNull(result)
verify(apiClient).get<User>("/users?email=$email")
}
}
Key Features
Compose-First UI
Jetpack Compose patterns for declarative UI with theming and accessibility
Coroutine Concurrency
Lifecycle-aware coroutines and Flow for async data and state
Clean Architecture
Separation of concerns with ViewModel, Repository, and Use Cases
Security & Permissions
Safe permissions handling, input validation, and secure storage
Testing Built-In
Unit, integration, and UI tests with JUnit, Espresso, and Robolectric
Performance Focus
Optimized rendering, caching, and data access for mobile
Installation
Choose Your IDE
Select the appropriate file path based on your development environment.
Create the Rules File
Create the cursor rules file in your project:
Create file: .cursor/rules/kotlin.mdc
Add the Rules Configuration
Copy the rules configuration below into your newly created file.
Start Coding
Your AI assistant will now follow Kotlin best practices automatically.
Kotlin-Specific Rules
Cursor rules in Kotlin provide intelligent navigation and manipulation capabilities designed specifically for Android development with Kotlin. These rules help you work more efficiently with Kotlin's unique features, Jetpack Compose, and Android-specific code.
Code Navigation
- Navigate between class and function definitions
- Jump to Compose composable functions
- Move between coroutine scopes and suspending functions
- Quick access to Android lifecycle methods
Smart Selection
- Select Compose UI blocks and modifiers
- Expand selection to include property delegates
- Smart null-safe operator selection
- Extension function navigation
Code Manipulation
- Quick composable function insertion
- Automated coroutine scope handling
- Android component lifecycle management
- Smart cast and safe call handling
Use Cases
Android Apps
Modern Android apps with Compose UI, coroutines, and MVVM architecture
API Clients
Robust API clients with Retrofit, OkHttp, and Flow-based data
Data Persistence
Room database with transactions, migrations, and caching strategies
Background Work
WorkManager jobs with constraints, retries, and lifecycle awareness
Standards Reference
| Standard | Description | Enforcement |
|---|---|---|
| Kotlin Conventions | Idiomatic Kotlin style and naming | Required across codebase |
| KDoc | Documentation for classes and functions | Required where applicable |
| Testing | Unit, integration, and UI coverage | Auto-generated patterns |
| Security | Permissions, input validation, secure storage | Built into patterns |
| Architecture | MVVM, repositories, use cases | Enforced via structure |
Note:
Combine these rules with ktlint and Detekt for maximum code quality enforcement.
Best Practices
- Use Compose-aware navigation
- Leverage coroutine-specific cursor movements
- Utilize Kotlin's smart cast features
- Navigate efficiently through Android components
Examples
// Navigate between composable functions
@Composable
fun CustomButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Button(
onClick = onClick,
modifier = modifier
) {
Text(text = text)
}
}
// Smart selection of coroutines and Android lifecycle
class MainViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UiState.Loading)
val uiState: StateFlow = _uiState.asStateFlow()
fun fetchData() {
viewModelScope.launch {
try {
val result = repository.getData()
_uiState.value = UiState.Success(result)
} catch (e: Exception) {
_uiState.value = UiState.Error(e.message)
}
}
}
}
Configuration
Customize Kotlin-specific cursor rules in your settings:
{
"kotlin.cursorRules": {
"composeNavigation": true,
"coroutineAware": true,
"androidLifecycle": true,
"nullSafety": true
}
}
Related Articles
Related Articles
Elixir Cursor Rules: AI-Powered Development Best Practices
Cursor rules for Elixir development enforcing official style guides, modern Elixir 1.12+ features, and clean code principles with AI assistance for production-ready code.
Python Cursor Rules: AI-Powered Development Best Practices
Cursor rules for Python development enforcing PEP 8 standards, modern Python features, and clean code principles with AI assistance for production-ready code.
Astro Cursor Rules: Islands Architecture & Static Content
Comprehensive Astro cursor rules covering component islands, static generation, content collections, and hydration directives for fast, SEO-friendly sites.