Replies: 4 comments 1 reply
-
This idea duplicates the one discussed in #297. |
Beta Was this translation helpful? Give feedback.
-
The name
|
Beta Was this translation helpful? Give feedback.
-
Another good alternative is to use the following convention for creating objects:
Here's an example for the private fun main() {
val value = "Hello world"
val text: NotBlankString = NotBlankString.orNull(value)
?: error("String shouldn't be blank")
println(text) // Hello world
}
/** Represents a string having at least one character, excluding whitespaces. */
public class NotBlankString private constructor(private val value: String) {
init {
require(value.isNotBlank()) {
"String shouldn't be blank"
}
}
/** Returns this string as [String]. */
override fun toString(): String = value
/** Contains static declarations for the [NotBlankString] type. */
public companion object {
/**
* Creates an instance of [NotBlankString] with the specified [value],
* or returns `null` if the [value] is [blank][CharSequence.isBlank].
*/
public fun orNull(value: CharSequence): NotBlankString? =
if (value.isBlank()) null
else NotBlankString("$value")
}
} |
Beta Was this translation helpful? Give feedback.
-
This idea is duplicated by #335. |
Beta Was this translation helpful? Give feedback.
-
🤔 The problem
The current stable API provides factory functions encapsulating their result in a Result type.
This is for example the case for the
toNonZeroInt
factory function:But this practice increases the complexity of the API by using a concept that is not widely accepted in the Kotlin community.
Also, the current factory functions being declared as public extension functions, they pollute the API and are not scoped within their context in the API reference.
💡 The idea
For improving our representation of a possible failure, Kotools Types should represent them with the
null
expression, modeling an absence of value in Java and Kotlin.Also, the factory functions should be provided in the
companion object
of the target type.Here's an example for the
NonZeroInt
type:Finally, factory functions of the library should have the following naming conventions:
create
- creates an instance of a given type from the specified input.createOrNull
- creates an instance of a given type from the specified input, or returnsnull
if the input is invalid.✅ Checklist
Here's the checklist to address for implementing this idea:
create*
for all types #316OrNull
orOrThrow
#258create*
for stable types #321Result
#263Result
to error level #265Result
to hidden level #266Result
#267ResultContext
#264ResultContext
to error level #268ResultContext
to hidden level #269ResultContext
#270🙏 Help needed
Please give this post a reaction if you are interested in this change and comment below your thoughts on it.
We would love to have your feedback!
Beta Was this translation helpful? Give feedback.
All reactions