Kotlin Standards
Kotlin Standards
Section titled “Kotlin Standards”1. Build System
Section titled “1. Build System”- Tool:
Gradlewith Kotlin DSL. Use Kotlin 1.9+. - Version: Target JVM 17+ or Kotlin/Native, Kotlin/JS as appropriate.
- Dependencies: Declare in
build.gradle.kts. Use version catalogs.
2. Code Style
Section titled “2. Code Style”- Formatter:
ktlintor IntelliJ formatter. Line length 120. - Linter:
detektfor static analysis. - Type Checker: Compiler strict mode. Use null safety features.
Gradle Configuration
Section titled “Gradle Configuration”tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { kotlinOptions { jvmTarget = "17" freeCompilerArgs = listOf("-Xjsr305=strict") }}3. Naming Conventions
Section titled “3. Naming Conventions”- Packages:
com.company.project.layer(lowercase) - Classes/Objects:
PascalCase - Functions/Variables:
camelCase - Constants:
UPPER_SNAKE_CASEorconst valin companion objects - Private Properties:
camelCase(no underscore prefix)
4. Project Structure
Section titled “4. Project Structure”src/├── main/│ ├── kotlin/│ │ └── com/company/project/│ │ ├── domain/│ │ │ ├── entities/│ │ │ └── valueobjects/│ │ ├── application/│ │ │ ├── usecases/│ │ │ └── interfaces/│ │ └── infrastructure/│ │ └── persistence/│ └── resources/└── test/ └── kotlin/ # Mirror main structure5. Language Features
Section titled “5. Language Features”- Immutability: Prefer
valovervar. Usedata classfor value objects. - Null Safety: Leverage nullable types (
String?). Use?.,?:,!!judiciously. - Sealed Classes: Use
sealed classorsealed interfacefor restricted hierarchies. - Extension Functions: Use for utility functions. Keep in appropriate packages.
Example
Section titled “Example”data class Email(val value: String) { init { require(value.matches(Regex("^[^@]+@[^@]+\\.[^@]+$"))) { "Invalid email: $value" } }}
sealed interface Result<out T> { data class Success<T>(val data: T) : Result<T> data class Failure(val error: Throwable) : Result<Nothing>}6. Dependency Injection
Section titled “6. Dependency Injection”- Framework: Use
KoinorKodeinfor Kotlin-native DI. Spring also supported. - Style: Prefer constructor injection. Use property injection sparingly.
7. Testing
Section titled “7. Testing”- Framework:
JUnit 5withkotestorspekfor BDD-style tests. - Assertions: Use
kotestmatchers orassertk. - Mocking:
MockKfor mocking. Usemockk()andevery {}.
Test Structure
Section titled “Test Structure”class UserServiceTest { private val userRepository = mockk<UserRepository>() private val userService = UserService(userRepository)
@Test fun `should create user with valid email`() { // Given val email = "test@example.com"
// When val user = userService.createUser(email, "Test User")
// Then user.email shouldBe email }}8. Error Handling
Section titled “8. Error Handling”- Exceptions: Use typed exceptions. Prefer
Result<T>for functional error handling. - Domain Exceptions: Unchecked exceptions extending
RuntimeExceptionor custom sealed classes. - Context: Include cause and context in exceptions.
sealed class DomainException(message: String, cause: Throwable? = null) : RuntimeException(message, cause) {
class InvalidEmailException(email: String) : DomainException("Invalid email: $email")}9. Collections & Sequences
Section titled “9. Collections & Sequences”- Immutable Collections: Prefer
listOf(),setOf(),mapOf(). - Mutable Collections: Use
mutableListOf()only when mutation is required. - Sequences: Use
sequence {}for lazy transformations of large collections.
10. Coroutines
Section titled “10. Coroutines”- Use When: Async operations, I/O-bound tasks.
- Scope: Use
CoroutineScopeand structured concurrency. - Suspending Functions: Mark async functions with
suspend. UseFlowfor streams.
suspend fun fetchUser(id: String): User = withContext(Dispatchers.IO) { userRepository.findById(id) ?: throw UserNotFoundException(id)}11. Dependencies
Section titled “11. Dependencies”Common Libraries
Section titled “Common Libraries”- HTTP:
ktor-clientorOkHttpwithRetrofit - Database:
Exposed(SQL),Room(Android) - JSON:
kotlinx.serializationorGson - Logging:
kotlin-loggingwrapper for SLF4J
12. Documentation
Section titled “12. Documentation”- KDoc: Use KDoc format (similar to JavaDoc). Required for public APIs.
- Format: Use
@param,@return,@throwstags.
/** * Creates a new user with validated email address. * * @param email valid email address (must match RFC 5322) * @param name user's full name (non-null, non-empty) * @return new User entity instance * @throws InvalidEmailException if email format is invalid */fun createUser(email: String, name: String): User { // Implementation}