Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[refined-type plugin] Kotlin Serialization can create invalid state of a refined type. #821

Open
lenguyenthanh opened this issue Jun 2, 2021 · 0 comments

Comments

@lenguyenthanh
Copy link

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants