christophsturm
06/10/2021, 11:54 AMspand
06/10/2021, 12:30 PMmissingDelimiterValue isnt String?ephemient
06/10/2021, 12:39 PMString? because then every use would have have to deal with potential null resultspand
06/10/2021, 12:41 PMfun <R : String?> String.substringAfter(..., missingDelimiterValue: R = this) : Rspand
06/10/2021, 12:42 PMephemient
06/11/2021, 4:28 AMMap.getOrDefault mirrors a Java API and requires @UnsafeVariance due to being in in+out position. Kotlin stdlib methods take a lambda for default, e.g. getOrElseephemient
06/11/2021, 4:32 AMfun <R : String?> String.substringAfter(..., missingDelimiterValue: R = this) : R, give it a shot and you'll see
ERROR Type mismatch: inferred type is String but R was expectedephemient
06/11/2021, 4:36 AMR is a supertype of String?, not a subtype, but that can't be expressedchristophsturm
06/11/2021, 7:16 AMchristophsturm
06/11/2021, 7:17 AMprivate fun <R:String?> String.substringAfter(delimiter: String, default:R): R {
val index = indexOf(delimiter)
return if (index == -1) default else substring(index + delimiter.length, length) as R
}
fun main() {
val nullable : String? = "nullable".substringAfter("null", null)
val nonNullable : String = "nullable".substringAfter("null", "notNull")
}
this worksephemient
06/11/2021, 7:19 AMmapOf<String, String>("a" to "b").getOrElse("c") { 0 } is Any worksephemient
06/11/2021, 7:19 AMstring.ifEmpty { charSequence } worksephemient
06/11/2021, 7:20 AMchristophsturm
06/11/2021, 7:23 AMchristophsturm
06/11/2021, 7:23 AMspand
06/11/2021, 7:25 AMchristophsturm
06/11/2021, 7:28 AMspand
06/11/2021, 7:43 AMchristophsturm
06/11/2021, 7:47 AMchristophsturm
06/11/2021, 7:47 AMsubStringAfterOrNullchristophsturm
06/11/2021, 7:51 AMchristophsturm
06/11/2021, 7:53 AMfun <R:String?> String.substringAfter(delimiter: String, default:R = this as R): R {
val index = indexOf(delimiter)
return if (index == -1) default else substring(index + delimiter.length, length) as R
}christophsturm
06/11/2021, 7:53 AMephemient
06/11/2021, 7:58 AM.substringAfter("", charSequence). the existing method can't either, but Kotlin's other get-or-else all handle similar cases fineephemient
06/11/2021, 8:00 AMinline fun <R> String.substringAfter(delimiter: String, default: () -> R): R where String : R = ...
fun String.substringAfter(delimiter: String): String = substringAfter(delimiter) { this }
but that where clause is not legalchristophsturm
06/11/2021, 8:30 AMchristophsturm
06/11/2021, 8:33 AMfun <R:CharSequence?> CharSequence.substringAfter(delimiter: String, default:R = this as R): R {
val index = indexOf(delimiter)
return if (index == -1) default else substring(index + delimiter.length, length) as R
}spand
06/11/2021, 11:59 AMfun <R:String?> String.substringAfter(delimiter: String, default:R = this as R): R