ant2009
ant2009

Reputation: 22486

Force parameter to be specific types that can be passed into a method

Android 3.5
Kotlin 1.3

I have the following method that passes in a parameter that could be VISIBLE, INVISIBLE, or GONE

fun setPromotionVisibility(Int: toVisiblity) {
    tvPromoation.visibility = toVisibility
}

However, when I call this method I could pass in any Int that might not be a visibility i.e.

setPromotionVisibility(234)

instead of doing this:

setPromotionVisibility(View.VISIBLE)

Just wondering if there anything I could do to force the user of the method to only enter VISIBLE, INVISIBLE, or GONE

Many thanks in advance

Upvotes: 2

Views: 452

Answers (3)

RelaxedSoul
RelaxedSoul

Reputation: 673

I don't know if it is useful for your case, but in my projects, I almost never use INVISIBLE.

So, I made an extension function

fun View.visible(value: Boolean) {
    visibility = if (value) View.VISIBLE else View.GONE
}

It also can be better:

fun View.visible(value: Boolean, animated: Boolean = false) {
    if (animated) {
        if (value) animate().alpha(1F).withStartAction { visibility = View.VISIBILE } 
        else animate().alpha(0F).withEndAction { visibility = View.GONE }
    } else visibility = if (value) View.VISIBLE else View.GONE
}

Upvotes: 2

tynn
tynn

Reputation: 39843

You can create a type-safe approach with an enum:

enum class Visibility(
    val asInt: Int
) {
    VISIBLE(View.VISIBLE),
    INVISIBLE(View.INVISIBLE),
    GONE(View.GONE),
}

which you then use as a parameter type:

fun setPromotionVisibility(toVisiblity: Visibility) {
    tvPromoation.visibility = toVisibility.asInt
}

Upvotes: 5

Jignesh Mayani
Jignesh Mayani

Reputation: 7193

Use Annotation for this

@IntDef({View.VISIBLE, View.INVISIBLE, View.GONE})
@Retention(RetentionPolicy.SOURCE)
public @interface Visibility {}

fun setPromotionVisibility(@Visibility toVisiblity: Int) {
tvPromoation.visibility = toVisibility
}

Upvotes: 3

Related Questions