Kotlin库项目编译报错:Failed resolution of: [Lkotlin/reflect/KProperty
Failed resolution of: [Lkotlin/reflect/KProperty with Your Kotlin Library's .aar Hey there! Let's dig into why this error pops up when using your Kotlin library's .aar in another project, specifically tied to the by lazy delegate.
Root Cause
The default implementation of by lazy (using LazyThreadSafetyMode.SYNCHRONIZED) relies on the Kotlin Reflection library (kotlin-reflect). It uses reflection to retrieve the KProperty object associated with the lazy property, which is required for its internal logic.
Here's the catch: When you package your library as an .aar, if the kotlin-reflect dependency isn't properly configured to be passed along to consuming projects, those projects won't have access to the reflection classes at runtime—hence the missing class error.
Common Culprits in Your Setup
1. Incorrect Gradle Dependency Scope
If your library's build.gradle/build.gradle.kts uses a restricted scope for kotlin-reflect, like compileOnly or testImplementation, the dependency won't be included in the .aar's transitive dependencies. For example:
// This will cause issues for consuming projects compileOnly "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
Consuming projects won't pull in kotlin-reflect automatically, leading to runtime failures.
2. Using the Default by lazy Implementation
As mentioned, the default synchronized lazy delegate requires reflection. If you don't need thread safety for that specific property, you're unnecessarily pulling in the reflection dependency.
Fixes to Try
Fix 1: Expose kotlin-reflect as a Transitive Dependency
Update your library's Gradle config to use api (or implementation) for kotlin-reflect, so it gets passed along to any project using your .aar:
// build.gradle (Groovy) api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" // build.gradle.kts (Kotlin) api("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
api ensures the dependency is visible to consumers, while implementation works in most cases too—api is just more explicit for dependencies your library's public API relies on.
Fix 2: Use a Reflection-Free lazy Implementation
If you don't need thread-safe lazy initialization, switch to LazyThreadSafetyMode.NONE (for single-threaded contexts) or PUBLICATION (for cases where multiple threads might initialize but you only need one result). These modes don't use reflection, so you can skip adding kotlin-reflect entirely:
// No reflection needed here val myLazyValue by lazy(LazyThreadSafetyMode.NONE) { // Your initialization logic }
Verification Steps
After making either change:
- Clean and rebuild your library project to generate a fresh .aar.
- Update the .aar reference in your test project.
- Clean the test project's build cache and recompile/runtime it. The error should be gone!
内容的提问来源于stack exchange,提问作者dgngulcan

