Skip to content

Refactor findDefaultCreator #858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions release-notes/CREDITS-2.x
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Contributors:
# 2.19.0 (not yet released)

WrongWrong (@k163377)
* #858: Refactor findDefaultCreator
* #839: Remove useKotlinPropertyNameForGetter and unify with kotlinPropertyNameAsImplicitName
* #835: Remove old SingletonSupport class and unified with KotlinFeature.SingletonSupport

Expand Down
1 change: 1 addition & 0 deletions release-notes/VERSION-2.x
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Co-maintainers:

2.19.0 (not yet released)

#858: Minor performance improvement of findDefaultCreator in edge cases.
#839: Remove useKotlinPropertyNameForGetter and unify with kotlinPropertyNameAsImplicitName.
#835: Remove old SingletonSupport class and unified with KotlinFeature.SingletonSupport.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,11 @@ internal class KotlinNamesAnnotationIntrospector(
): PotentialCreator? {
val kClass = valueClass.creatableKotlinClass() ?: return null

val propertyNames = kClass.memberProperties.map { it.name }.toSet()

val defaultCreator = kClass.let { _ ->
// By default, the primary constructor or the only publicly available constructor may be used
val ctor = kClass.primaryConstructor ?: kClass.constructors.takeIf { it.size == 1 }?.single()
ctor?.takeIf { it.isPossibleCreator(propertyNames) }
}
val defaultCreator = kClass.primarilyConstructor()
?.takeIf { ctor ->
val propertyNames = kClass.memberProperties.map { it.name }.toSet()
ctor.isPossibleCreator(propertyNames)
}
?: return null

return declaredConstructors.find {
Expand All @@ -115,6 +113,9 @@ private fun AnnotatedClass.creatableKotlinClass(): KClass<*>? = annotated
.takeIf { it.isKotlinClass() && !it.isEnum }
?.kotlin

// By default, the primary constructor or the only publicly available constructor may be used
private fun KClass<*>.primarilyConstructor() = primaryConstructor ?: constructors.singleOrNull()

private fun KFunction<*>.isPossibleCreator(propertyNames: Set<String>): Boolean = 0 < parameters.size
&& !isPossibleSingleString(propertyNames)
&& parameters.none { it.name == null }
Expand Down