Phani Mahesh
05/17/2022, 7:43 AMJoffrey
05/17/2022, 7:52 AMRoukanken
05/17/2022, 7:54 AMclass Collection<T> {
fun getOrElse(key: Int, default: T & Any): T & Any
}
Phani Mahesh
05/17/2022, 7:57 AMTobias Suchalla
05/17/2022, 8:17 AMfun <T> getOrDefault(nullable: T, default: T & Any): T & Any
Edit: You just used the same example in the channel, mea culpa...Vampire
05/17/2022, 8:36 AMx
is still nullable, isn't it?
Where is the difference between the two examples of OP besides the second one being more readable and looking more idiomatic?Ruckus
05/17/2022, 4:40 PMfun <T: Any> getOrDefault(nullable: T?, default: T): T
Vampire
05/17/2022, 4:53 PMRuckus
05/17/2022, 5:04 PMVampire
05/17/2022, 7:15 PMRuckus
05/17/2022, 7:19 PMTobias Suchalla
05/18/2022, 5:39 AMDan Fingal-Surma
05/18/2022, 9:08 AMJoffrey
05/18/2022, 3:03 PMThe getOrElse posted above also qualifies, as you cannot correctly introduce a new type parameter there.The
getOrElse
above is a member function, which means if you control it you also control the class itself. You could declare the class with T : Any
and add T?
everywhere instead of T
, and use T
instead of T & Any
.Now add Bar as a val of Foo without modifying Foo's type parameter.You control
Foo
here, so you can change `Foo`'s parameter (and again, update all T
to T?
).
Or do you mean it's about backwards compatibility? That could be a fair point.Dan Fingal-Surma
05/18/2022, 3:38 PMJoffrey
05/18/2022, 3:42 PMColumnType<String>
from ColumnType<String?>
, and yet be able to represent the non-nullable KClass<String>
in both cases. That makes sense, thanks!Roukanken
05/18/2022, 3:42 PMJoffrey
05/18/2022, 3:44 PMChanging <T> to <T : Any> and adding T? places does not in general retain the same semantics, as you have introduced definitely nullable types where they were not before.Indeed, for some reason I missed this.
Dan Fingal-Surma
05/18/2022, 3:45 PMJoffrey
05/18/2022, 3:49 PM<T : Any>
(since the function itself is generic and only takes T
as input, it is safe to introduce definitely nullable type):
https://kotlinlang.slack.com/archives/C0B8MA7FA/p1652773490430979