Kotlin: Implement and use singleOrNullSubType

Pulls another cast out into a utility function.
This commit is contained in:
Ian Lynagh
2022-08-30 18:31:01 +01:00
parent f5d43b80ed
commit 6f82b06bd7
2 changed files with 14 additions and 4 deletions

View File

@@ -1169,7 +1169,7 @@ open class KotlinUsesExtractor(
"kotlin.Boolean", "kotlin.Byte", "kotlin.Char", "kotlin.Double", "kotlin.Float", "kotlin.Int", "kotlin.Long", "kotlin.Number", "kotlin.Short"
)
private fun kotlinFunctionToJavaEquivalent(f: IrFunction, noReplace: Boolean) =
private fun kotlinFunctionToJavaEquivalent(f: IrFunction, noReplace: Boolean): IrFunction =
if (noReplace)
f
else
@@ -1186,8 +1186,7 @@ open class KotlinUsesExtractor(
decl.valueParameters.zip(f.valueParameters).all { p -> p.first.type.classifierOrNull == p.second.type.classifierOrNull }
} ?:
// Or if there is none, look for the only viable overload
javaClass.declarations.singleOrNull { decl ->
decl is IrFunction &&
javaClass.declarations.singleOrNullSubType<IrFunction> { decl ->
decl.name == f.name &&
decl.valueParameters.size == f.valueParameters.size
} ?:
@@ -1213,7 +1212,7 @@ open class KotlinUsesExtractor(
else
null
}
} as IrFunction? ?: f
} ?: f
fun <T: DbCallable> useFunction(f: IrFunction, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>? = null, noReplace: Boolean = false): Label<out T> {
return useFunction(f, null, classTypeArgsIncludingOuterClasses, noReplace)

View File

@@ -13,3 +13,14 @@ inline fun <reified S: IrDeclaration> Iterable<IrDeclaration>.findSubType(
return this.find { it is S && predicate(it) } as S?
}
/**
* This behaves the same as Iterable<IrDeclaration>.singleOrNull, but
* requires that the value found is of the subtype S, and it casts
* the result for you appropriately.
*/
inline fun <reified S: IrDeclaration> Iterable<IrDeclaration>.singleOrNullSubType(
predicate: (S) -> Boolean
): S? {
return this.singleOrNull { it is S && predicate(it) } as S?
}