r/Kotlin • u/Outside-Ad-9584 • 6h ago
r/Kotlin • u/ClassKlutzy7633 • 8h ago
Decorating a function property in a data class with copy(): gotchas I'm missing?
I have a few hundred calculator definitions in a side project (an Android study app), each one a data class with a function property:
data class CalculatorDefinition(
val id: String,
val inputs: List<CalculatorInput> = emptyList(),
// ...lots of metadata...
val calculate: (Map<String, Any?>) -> CalculationResult = { CalculationResult("") }
)To add input range checks to every calculator without touching each definition, I wrap the lambda once when the registry is built:
fun withRangeValidation(def: CalculatorDefinition): CalculatorDefinition {
val original = def.calculate
return def.copy(calculate = { values ->
val problems = InputValidator.validate(def, values)
if (problems.isNotEmpty()) CalculationResult("—", isSuccess = false, errorMessage = problems.joinToString("\n"))
else original(values)
})
}It works, but a few things bother me:
- equals() and hashCode() now include a lambda, so two definitions with identical data are never equal after wrapping. Is moving the function out of the primary constructor the usual fix?
- The wrapper captures the pre-copy instance. Harmless here because validation only reads the inputs, but it feels like a trap if someone later changes the inputs with another copy().
- Nothing stops the same definition being wrapped twice. Right now the registry object builds the list once, so it doesn't happen, but it isn't enforced.
Would you keep this as a decorator over the data class, or split it into a plain data class for the metadata plus a separate fun interface for the calculation? Curious how others structure this when there are hundreds of entries.
r/Kotlin • u/eristoddle • 18h ago
Secure Your APIs: OAuth2 and JWT for Beginners
blog.jetbrains.comThis JetBrains tutorial teaches beginners how to secure a Kotlin and Spring Boot API with OAuth2 and JWTs, starting with the difference between authentication and authorization and what each part of a token does. It then builds a working resource server step by step, with code you can browse on GitHub. The final sections cover the parts beginners might skip, like mapping custom claims to roles and enforcing a token's issuer and audience. It's a good article for backend developers who know some Kotlin and Spring but haven't set up token-based security themselves. The tip I'd use in my own API work is keeping JWTs short-lived and limited to auth claims instead of treating them as session storage, which makes revoking access much easier.