Skip to content

Conversion from base types #37

@serras

Description

@serras

(From a conversation on Slack)

The idea is to automatically provide conversions or constructors from basic types to classes with invariants.Some ideas:

  • For value class we create from the base type to the type with invariants, as in the case above. Maybe we should return String? instead.
@JvmInline
value class String5(val value: String) {
    init {
        require(value.length < 5)
    }
}

fun String.asString5() = if (this.length < 5) {
    String5(this).right()
} else {
    "String '$this' should be smaller than 5".left()
}
  • Conversely, we could add pseudo-constructors in the companion object which return the type but nullable.
@JvmInline
value class String5(val value: String) {
    init {
        require(value.length < 5)
    }

    companion object {
        fun attempt(value: String): String5? = ...
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions