3

I am trying IntDef typedef to restrict the specific type of parameter to the function. But when I am using IntDef using java it's working properly but at the same time, it's not working with kotlin. Below is my code snippet -

In JAVA -

@IntDef({CASH,WITHDRAW}) 
@Retention(RetentionPolicy.SOURCE) 
public @interface TransTypeJava { 
int CASH = 1; int WITHDRAW = 2;
}

In Kotlin -

const val CASH = 1 const val WITHDRAW = 2 
@IntDef(CASH, WITHDRAW) 
@kotlin.annotation.Retention(AnnotationRetention.SOURCE) 
internal annotation class TransTypeKotlin

Using in class -

override fun onCreate(savedInstanceState: Bundle?) { 
super.onCreate(savedInstanceState) 
setContentView(R.layout.activity_main) 
demo(TransTypeJava.CASH)// Working 
demo(1) // Showing compile time error 
} 
fun demo(@TransTypeJava type:Int){}

Calling to the demo function gives me an error saying that Must be one of: TransTypeJava.CASH, TransTypeJava.WITHDRAW by passing value other than TransTypeJava type.

override fun onCreate(savedInstanceState: Bundle?) { 
super.onCreate(savedInstanceState) 
setContentView(R.layout.activity_main) 
demo(TransTypeKotlin.CASH) //Working 
demo(1) // Working 
} 
fun demo(@TransTypeKotlin type: Int){} 

While using this with kotlin it does not show any error by passing value other than TransTypeKotlin type. Any help will be appreciated.

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
sanil
  • 482
  • 1
  • 7
  • 23

1 Answers1

-1

Try out with this

@IntDef(MALE, FEMALE)
@Retention(AnnotationRetention.SOURCE)
annotation class UserRoleType {
    companion object {
        const val MALE = 1
        const val FEMALE = 2
    }
}
Akshay Raiyani
  • 1,243
  • 9
  • 21
  • I used it in my live project and it's perfectly working for me. which type of error do you face while you use this? – Akshay Raiyani Sep 24 '19 at 10:16
  • Compiler doesn't shows me error even i am passing value other than specified type – sanil Sep 24 '19 at 10:19
  • strange!! Anyway, let me know if you need any help on that :) – Akshay Raiyani Sep 24 '19 at 10:58
  • Can you please share the pseudo code of function in which you have implemented this and also the code for calling the same function – sanil Sep 24 '19 at 11:11
  • private fun getUserType(userRoleType: Int){ if(userRoleType == UserRoleType1.MALE){ Log.d("Male", UserRoleType1.MALE.toString()) }else if(userRoleType == UserRoleType1.FEMALE){ Log.d("FEMALE", UserRoleType1.MALE.toString()) } } I called this function like this - getUserType(UserRoleType1.MALE) – Akshay Raiyani Sep 24 '19 at 11:40
  • In your case you have not specified the parameter type in the function. – sanil Sep 24 '19 at 11:50