思いつきで書いたkotlinのコード
別に意味は無い
internal fun enumConditon() {
val noString = ConditionData("")
assertEquals(noString.enum, CDEnum.NOSTRING)
assertEquals("ERROR", perocessData(noString))
assertEquals("strが空です", getMessage(noString))
}
sealed interface DataAddType
class OK: DataAddType
class ERROR: DataAddType
class MISSING: DataAddType
data class ConditionData(
val str: String
) {
val enum: CDEnum = CDEnum.test(this)
}
enum class CDEnum(val condition: (ConditionData) -> Boolean,val addType: DataAddType, val msg: String){
OK(
{it.str.isNotBlank() && 10 <= it.str.length && it.str.length < 50}, OK(), ""
),
NOSTRING(
{it.str.isBlank()}, ERROR(), "strが空です"
),
LENGTH_OVER(
{it.str.isNotBlank() && 50 < it.str.length}, ERROR() ,"strの文字長がオーバーしてます"
),
LENGTH_MINI(
{it.str.isNotBlank() && it.str.length < 10}, ERROR(), "strの文字長が不足してます"
),
MISSING({true}, MISSING(), "判断外のエラーです");
companion object {
fun test(data: ConditionData): CDEnum = values().first { it.condition(data) }
}
}
fun perocessData(data: ConditionData): String {
return when (data.enum.addType) {
is OK -> "OK"
is ERROR -> "ERROR"
is MISSING -> "MISSING"
}
}
fun getMessage(data: ConditionData): String = data.enum.msg