AI Rules for Kotlin
Guide for effective AI interaction patterns when working with Kotlin and Android development.
Kotlin Rules
.cusor/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
### Framework 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
```java
/**
* 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 `should find user by email when user exists`() = runTest {
// Given
val email = "[email protected]"
val user = User(id = 1, email = email)
whenever(apiClient.get<User>("/users?email=$email")).thenReturn(user)
// When
val result = service.findUserByEmail(email).first()
// Then
assertNotNull(result)
assertEquals(email, result?.email)
verify(apiClient).get<User>("/users?email=$email")
}
@Test
fun `should return null when user not found`() = runTest {
// Given
val email = "[email protected]"
whenever(apiClient.get<User>("/users?email=$email")).thenReturn(null)
// When
val result = service.findUserByEmail(email).first()
// Then
assertNull(result)
verify(apiClient).get<User>("/users?email=$email")
}
}
## 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
## Best Practices
- Use Compose-aware navigation
- Leverage coroutine-specific cursor movements
- Utilize Kotlin's smart cast features
- Navigate efficiently through Android components
## Examples
```kotlin
// 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>(UiState.Loading)
val uiState: StateFlow<UiState> = _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
Language-Specific Rules
Modern AI-powered IDEs provide intelligent language-specific features and rules that enhance your coding experience across different programming languages. This guide covers capabilities across tools like GitHub Copilot, Cursor, and other AI coding assistants.
AI Rules for PHP
Guide for effective AI interaction patterns when working with PHP code.
Mobile Framework Guidelines
Framework-specific guidelines for mobile development across React Native, Flutter, Swift, and Kotlin.