Type parameter problem with Nullable and Not-Nullable


#1

hi, the following code shows no error in IDE.

fun <X:Any,T:X?> T.ifNotNull(f:(x:X)->Unit):T{   if(this!=null) {   f(this)   // not null !   }   return this }

val items : MutableList<CartItem> …

ShoppingCart load product.code ifNotNull {
  items add it
}

But the compiler throws :

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: internal fun <X : jet.Any, T : X?> T.ifNotNull(f: (X) -> jet.Unit): T defined in name.my.store.service

Why?

For now I have to change back to this version :

fun <T> T.ifNotNull(f:(x:T)->Unit):T{   if(this!=null) {   f(this)   // still nullable   }   return this }

ShoppingCart load product.code ifNotNull {   items add it!!   // !! is needed here. }

is this a bug ?

BTW: I’m using  kotlin-compiler-0.1-20130802.155613-19.jar

Thanks.

Outersky


#2

OK, I'm such a idiot , this works:

``

fun <T:Any> T?.ifNotNull(f:(x:T)->Unit):T?{
  if(this!=null) {
  f(this)
  }
  return this
}


#3

Nevertheless your first example is a bug. I've created an issue about it (http://youtrack.jetbrains.com/issue/KT-3850).