Please help me to optimize this long If statement in Kotlin. I want to make it shorter as much as possible.
`if (locationType == 1) {
if (isPostDayOfWeeks) {
if (isPostLocation) {
Log.d("RefreshStatus", "PostLocation: " isPostLocation)
settingRepo.setLocationStatusText(true, endTime.toString())
} else {
if(isPostNextDayOfWeek()){
settingRepo.setLocationStatusText(false, startTime.toString())
}else{
settingRepo.setLocationStatusText(false, null)
}
Log.d("RefreshStatus", "PostLocation: $isPostLocation")
}
} else {
settingRepo.setLocationStatusText(false, null)
}
} else {
if (autoLocationSwitch) {
settingRepo.setLocationStatusText(true, null)
} else {
settingRepo.setLocationStatusText(false, null)
}
}`
CodePudding user response:
Does this help?
val (X, Y) = when {
locationType != 1 -> autoLocationSwitch to null
!isPostDayOfWeeks -> false to null
isPostLocation -> true to endTime.toString()
isPostNextDayOfWeek() -> false to startTime.toString()
else -> false to null
}
settingRepo.setLocationStatusText(X, Y)
Replace X
and Y
with proper names.
CodePudding user response:
You can also try this if clean or readability matters :
if (locationType != 1) {
settingRepo.setLocationStatusText(autoLocationSwitch, null);
return;
}
if (!isPostDayOfWeeks) {
settingRepo.setLocationStatusText(false, null);
return;
}
if (isPostLocation) {
settingRepo.setLocationStatusText(true, endTime.toString());
return;
}
settingRepo.setLocationStatusText(
false,
isPostNextDayOfWeek() ? startTime.toString() : null
);
Must wrap this code in method otherwise it may block some code to execute!
CodePudding user response:
You can use variables with default values to elide some of the branches:
boolean location = false;
String time = null;
if (locationType == 1) {
if (isPostDayOfWeeks) {
if (isPostLocation) {
Log.d("RefreshStatus", "PostLocation: " isPostLocation);
location = true;
time = endTime.toString();
} else if (isPostNextDayOfWeek()) {
time = startTime.toString();
}
}
} else {
location = autoLocationSwitch;
}
settingRepo.setLocationStatusText(location, time);