Generic type that is nullable

#1

Hi, I was trying to write a generic function but encounter a small problem.
The function I wrote is as below.

fun <Y,T1,T2> LiveData<T1>.combineLatest(another:LiveData<T2>, 
                                         combiner:(T1,T2) -> Y){
   val mediatorData = MediatorLiveData<Y>()
   var latestT1: T1? = null
   var latestT2: T2? = null
   var isT1Ready = false
   var isT2Ready = false
   mediatorLiveData.addSource(this) { it->
       latestT1 = it
       isT1Ready = true
       if(isT2Ready){
          mediator.value = combiner(it,latestT2) // Here would be problem, latestT2 is T2? not T2. So the type does not match. 
       }
   }
   ......
}

As comment indicated. combiner function would complain about Type mismatch. Combiner was expecting T2 rather than the placeholder’s T2?
And I do not want to use combine(it,latestT2!!). What if T2
is String? in runtime. And User is actually expecting to handle null inside his function?

But I do not want to force user write combiner as (T1?,T2?) -> Y, As the function should ensure the value supplied to combiner function is T1 and T2.

So, is there a way to achieve both?
Or do I need to handle <T1:Any, T2:Any> <T1:Any?,T2:Any?> seperately?
I am sure there should be an elegant way to achieve the result but I checked the generic documents and the content seems not helpful in this situation.

Best regards.

#2

You can cast it like this: latestT2 as T2. You will get an unchecked cast warning, which can be suppressed by adding @Suppress("UNCHECKED_CAST") on the line above.

1 Like
#3

Thanks!