我有一个使用“ ValidationRequirements”数据类来验证字符串的类,如果无效,则返回Enum错误消息。 根据传递的要求,枚举应调整字符串以使其匹配。
ValidationRequirements:
data class ValidationRequirements(
//--------CONFIG_REQUIREMENTS--------
val PREFIX_STRING: String,
val REQUIRED_LENGTH: Int,
val MAXIMUM_LENGTH: Int,
val REQUIRE_SPECIAL_CHARACTERS: Boolean,
val REQUIRE_DIGITS: Boolean,
val REQUIRE_LOWER_CASE: Boolean,
val REQUIRE_UPPER_CASE: Boolean,
val REQUIRE_SPACE_SEPARATION: Boolean
)
枚举:
enum class StringStrengthReport(private val errorMessage: String) {
INVALID_EMAIL_FORMAT("Invalid email format\n"),
TO_SHORT(" requires at least 6 characters\n"),
LOWER_CASE_REQUIRED(" requires at least one lower case character\n"),
UPPER_CASE_REQUIRED(" requires at least one upper case character\n"),
DIGIT_REQUIRED(" requires at least one numeric character\n"),
SPECIAL_CHARACTER_REQUIRED(" requires at least one special character (i.e !&?#%)\n"),
MAX_LENGTH_EXCEEDED(" max length is 32 characters\n"),
NULL_STRING(TO_SHORT.errorMessage),
VALID(" is valid!\n");
}
是否可以通过更改其他种类的弦的最小/最大长度的要求?
答案 0 :(得分:1)
改为使用密封类:
sealed class StringStrengthReport(private val message: String) {
override fun toString() = message
}
class InvalidEmailFormat(): StringStrengthReport("Invalid email format")
class TooShort(val minLength: Int): StringStrengthReport("Requires at least $minLength characters")
结果:
println(InvalidEmailFormat()) // Invalid email format
println(TooShort(7)) // Requires at least 7 characters
答案 1 :(得分:-1)
如果我需要将变量传递给枚举,那么从我的角度来看,实际上需要的是数据类,而不是枚举。