In Kotlin objects, there can be a conflict between...
# codereview
t
In Kotlin objects, there can be a conflict between property names and the type names of values. For example, in the following code, the
java
property conflicts with
java.time.OffsetDateTime
, resulting in an error message:
Unresolved reference 'time'.
Copy code
object MyObject {
    val java: Boolean = true
    val someTime: OffsetDateTime = java.time.OffsetDateTime.now()
}
I understand that this can be avoided in one of the following ways: • Change the property name
java
• Use import statements to avoid the fully qualified name • Create an alias for
java.time.LocalDateTime
and refer to it Is there any other way to resolve this issue? I am creating code generation tool, so I am looking for a solution that can be applied uniformly in all cases, rather than a workaround that is applied only under specific conditions.
I came up with a solution to create another object to hold the values:
Copy code
object __MyObject {
    val __java: Boolean = true
    val __someTime: OffsetDateTime = java.time.OffsetDateTime.now()
}

object MyObject {
    val java: Boolean = __MyObject.__java
    val someTime: OffsetDateTime = __MyObject.__someTime
}
Do you have any comments on this?
h
You can just use backticks:
Copy code
object MyObject {
    val java: Boolean = true
    val someTime: java.time.OffsetDateTime = `java.time`.OffsetDateTime.now()
}
❤️ 1
🤯 3
t
Thank you very much! I didn’t know we can use backticks for package names. This is very helpful.
k
It seems unfortunate that the Java designers chose the dot (.) to separate parts of a package name. Package names are not really hierarchical. The "java" part of "java.time" can't stand on its own, and there's no sibling relationship between packages "a.b" and "a.c" any more than there is between "a.b" and "c.d". So they've overloaded a punctuation character that is otherwise used to separate a field from an object, and given us this unforeseen headache.