arrow-meta
arrow-meta copied to clipboard
[refined-type plugin] Kotlin Serialization can create invalid state of a refined type.
Is your feature request related to a problem? Please describe. Kotlin Serialization and possibly other compiler plugins can create invalid state of a refined type.
Example:
@JvmInline
@Serializable
value class GameId private constructor(val value: String) {
companion object : Refined<String, GameId>(::GameId, {
ensure((it.length == 8) to "Expected $it has 8 characters")
})
}
@Serializable
data class Game(
val gameId: GameId,
val color: String,
)
fun main() {
val json = """{"gameId":"","color":"white"}"""
println(Json.decodeFromString<Game>(json))
}
// Invalid Output: Game(gameId=GameId(value=), color=white)
Describe the solution you'd like
Automating generate verify code in init
block for user:
value class GameId private constructor(val value: String) {
init {
val results = constraints(value)
if (!results.allValid())
throw IllegalArgumentException(renderMessages(results))
}
companion object : Refined<String, GameId>(::GameId, {
ensure((it.length == 8) to "Expected $it has 8 characters")
})
}```
**Describe alternatives you've considered**
We may also include the code when generating code. So user don't have to add this boilerplate.