Philipp Mayer
06/11/2020, 10:44 AMdata class SystemName(val value: String) {
init {
require(value == value.toLowerCase().capitalize()) { "Name $value must be capitalized!" }
}
Right now, when I create the Object I always check if its lowercase with the first letter being capital.
I'd like to let the object take care of .toLowercase().capitalize()
, so I don't have to do it on my own. Searching google gives me mixed results which don't look that clean tbh. What would be your take on this? Thanks ahead!
My current take is the following:
data class SystemName(val value: String) {
init {
require(value == value.toLowerCase().capitalize()) { "Name $value must be capitalized!" }
}
/**
* automatically converts string to required format
*/
companion object {
fun createInstance(name: String) = SystemName(name.toLowerCase().capitalize())
}
Hanno
06/11/2020, 12:00 PMPhilipp Mayer
06/11/2020, 2:45 PMHanno
06/11/2020, 3:59 PMPhilipp Mayer
06/11/2020, 4:15 PMreturn when (system.toString()) {
System.Abc.name -> dosmth
System.Def.name -> dosmth
else -> throw SystemNotFoundException("System $system could not be found")
}
Philipp Mayer
06/11/2020, 4:16 PMPhilipp Mayer
06/11/2020, 4:16 PMHanno
06/11/2020, 5:02 PMPhilipp Mayer
06/11/2020, 5:04 PMHanno
06/11/2020, 6:36 PMPhilipp Mayer
06/12/2020, 5:46 AMMatteo Mirk
06/12/2020, 10:01 AMenumValueOf(name)
but it throws if the string value doesnāt match. If you want a null in that case you can wrap it as a top-level function like this:
inline fun <reified E : Enum<E>> enumValueOrNull(name: String): E? = try {
enumValueOf<E>(name)
} catch (e: Exception) {
null
}
As for your doSth function, it could be defined inside the enum but consider if that behavior belongs to SystemName or not.Philipp Mayer
06/12/2020, 10:49 AMclass SystemName(val value: String) {
override fun toString(): String = value.toLowerCase().capitalize()
}
/**
* consists of all integrated systems
* used to determine the workflow on parsing and mapping the objects
*/
enum class System {
System1,
System2;
companion object {
fun of(systemName: SystemName): System = enumValueOf(systemName.toString())
}
}
class FindConfigurationService(
val findDataUsecase: FindDataUsecase,
val findOtherDataUseCase: FindOtherDataUseCase
) : FindConfigurationUseCase {
override fun getConfiguration(systemName: SystemName, id: ConfigId): Configuration =
when (System.of(systemName)) {
System.System1 -> findDataUsecase...
System.System2 -> findOtherDataUseCase...
}
}
It's working and I'm fine with that, but I'm definetly open for suggestions!Matteo Mirk
06/12/2020, 1:56 PMwhen
expression and simply have:
System.of(systemName).findUseCase()
Philipp Mayer
06/12/2020, 3:44 PMMatteo Mirk
06/15/2020, 10:27 AMPhilipp Mayer
06/15/2020, 2:38 PMHanno
06/15/2020, 5:04 PMMatteo Mirk
06/16/2020, 11:17 AM