Reputation: 3651
I have defined variable which is null but later on based on view.tag object type i have to set it.But it say Required Nothing found RequestCenterDetails
. Below is how i am trying to do this
holder?.addressIcon?.setOnClickListener {
val tagObject = holder.institutecardView.getTag(R.id.item_institute_cardview)
var center=null
if(tagObject is RequestCenterDetails)
{
Log.d("location","-------------TEST----------- its a RequestCenter")
center=tagObject as RequestCenterDetails // over here it say "Required Nothing found RequestCenterDetails"
}
else if(tagObject is Center)
{
Log.d("location","-------------TEST----------- its a Center")
}
Problem is that i have to take same action based on there field value but both object has different field names. Is there any better way to do this. I am new to kotlin.
Upvotes: 1
Views: 543
Reputation: 7472
You just need to specify type as it's not clear to the compiler, I'd recommend you to put the highest possible common possible type in hierarchy(for both RequestCenterDetails
and Center
) , or just Any
if you're okay to accept any type:
var center: Any = null
or
var center: CommonBaseClass = null
Upvotes: 0
Reputation: 22038
If you know center
will be RequestCenterDetails
, do
var center: RequestCenterDetails? = null
If center
can also be of another type, do
var center: Any? = null
A more concise version of what you're doing would be:
var center: RequestCenterdetails? = tagObject as? RequestCenterDetails
which assigns center the value of tagObject
if tagObject
is RequestRecenterDetails
, else assigns it null
.
Upvotes: 4
Reputation: 12177
The reason is, that your variable center
has the type Nothing?
.
You can change this by saying:
var center: Any? = null
But this is not advisable to work with such a generic type.
Upvotes: 1