Reputation: 15365
I have implemented the following method:
private fun String?.replaceHolder(item: String): String? {
return this?.replace("\$deployUnit", item)
}
The code that is using it looks like that:
val a = "aaa".replaceHolder("fff")
However, the inferred type of a is String?
.
With contracts I can say that if the return value is not null then subject was is not null like that:
@ExperimentalContracts
private fun String?.replaceHolder(item: String): String? {
contract {
returnsNotNull() implies (this@replaceHolder != null)
}
return this?.replace("\$deployUnit", item)
}
Is it possible to say the opposite? I mean to infer that the type of a
is not null? Is there another way to do that?
Upvotes: 3
Views: 308
Reputation: 1921
if i understand you well this is what you want
private fun <T: String?> T.replaceHolder(item: String): T {
return this?.replace("\$deployUnit", item) as T
}
T extends String? means that T type can be String or null or both and every type T is, function return that type too
Upvotes: 4