Question
What does the error 'Cannot import-on-demand from object' mean in Kotlin, and how can it be resolved?
Answer
The error 'Cannot import-on-demand from object' in Kotlin typically occurs when trying to use wildcard imports (e.g., `import packageName.*`) with an object that does not expose its members for import. This results in a compilation error, as Kotlin does not allow importing from an object in this manner.
// Example of valid import and usage of an object in Kotlin
// MyObject.kt
package com.example
object MyObject {
val greeting: String = "Hello, World!"
}
// Main.kt
import com.example.MyObject.greeting // Explicit import
fun main() {
println(greeting) // Correct usage of imported member.
}
Causes
- Attempting to perform a wildcard import from an object declaration.
- The object does not have public members to import.
- Issues with the visibility modifier of the object or its members.
Solutions
- Use explicit imports instead of wildcard imports, for example: `import packageName.ObjectName.propertyName` instead of `import packageName.*`.
- Ensure that the members of the object are public if you intend to access them.
- If wildcard imports are necessary, consider refactoring the object to a class or companion object with accessible members.
Common Mistakes
Mistake: Using wildcard import with an object without public members.
Solution: Switch to explicit imports to only reference the members you need.
Mistake: Forgetting to check visibility modifiers of object members.
Solution: Ensure that all members you wish to import are publicly accessible.
Helpers
- Kotlin import error
- Cannot import-on-demand from object
- Kotlin object members
- Kotlin wildcard imports
- Kotlin object visibility