Hello community! i want to share my implementation of the ternary operator hoping a constructive feedback to improve mi kotlin skills. see ya!
I use annotations to make the decision
@Target(AnnotationTarget.CLASS)
@Retention(RUNTIME)
annotation class ConditionAnnotation(val condition: Boolean = false)
@ConditionAnnotation(true)
class IfCondition
@ConditionAnnotation(false)
class ElseCondition
the inline functions then an orelse respone are selected depending of the condition
i must to take the dessision of check for previous annotations beacuse of the kotlin optimizations that returns the same instance for the lambda function paramters. I am thinking in crate those with an object instantiation
inline infix fun <reified T : Any> Boolean.then(ifResponse: T): T {
val annotations = ifResponse::class.annotations as MutableList
annotations.removeAll(annotations.filterIsInstance<ConditionAnnotation>())
annotations.add(
when (this) {
true ->
IfCondition()::class.java.getAnnotation(ConditionAnnotation::class.java)
false ->
ElseCondition()::class.java.getAnnotation(ConditionAnnotation::class.java)
}
)
return ifResponse
}
inline infix fun <reified T : Any> T.orElse(elseResponse: T): T {
return this::class.findAnnotation<ConditionAnnotation>()?.let {
if (!it.condition) elseResponse else this
} ?: this
}
inline infix fun <reified T : Any> T.orElse(elseResponse: T): T {
return this::class.findAnnotation<ConditionAnnotation>()?.let {
if (!it.condition) elseResponse else this
} ?: this
}
this is how the test looks
@Test
fun testTernary() {
then(true, "true", "false", "true")
then(true, "true", "false", "true")
then(false, "true", "false", "false")
then(true, 1, 0, 1)
then(false, 1, 0, 0)
then(true, MEDIATYPE.MOVIE, MEDIATYPE.TV, MEDIATYPE.MOVIE)
then(false, MEDIATYPE.MOVIE, MEDIATYPE.TV, MEDIATYPE.TV)
}
private inline fun <reified T : Any> then(condition: Boolean, ifCondition: T, elseCondition: T, expectedValue: T) {
Assert.assertEquals(condition.then(ifCondition).orElse(elseCondition), expectedValue)
//infix
Assert.assertEquals(condition then ifCondition orElse elseCondition, expectedValue)
}
i hope that someone finds this usseful