I wanna my `data class` to have non optional field...
# announcements
p
I wanna my
data class
to have non optional field, but to be able to initialize it with a nil, which will be replaced by a default value. Something like this:
Copy code
data class Text(val text: String) {
    constructor(textNullable: String?) : this(textNullable ?: "", nullable)
}
It works well on native, but on JVM I got following error:
Copy code
Platform declaration clash: The following declarations have the same JVM signature (<init>(Ljava/lang/String;)V):
    constructor Text(text: String) defined in ...
    constructor Text(textNullable: String?) defined in ...
Any way I can bypass it? I think I could replace
data class
with
class
to remove the default constructor, but in this case I’ll lose other data class advantages, like
copy(...)
r
one option is
fun Text(text: String?) = Text(text ?: "")
as a separate function
👍 1
n
What if you make the primary constructor private?
I would expect even with Jason's approach you'd still run into problems; the function call would be potentially ambiguous
Unless Kotlin gives preference to functions over constructors or something like that
a
Copy code
data class Text(val text: String="")
n
It looks like Kotlin indeed gives preference to the constructor, very spooky
r
either the non-nullable overload wouldn't be a candidate (if the argument type is nullable) or it would be preferred (if the argument type is non-nullable)
n
Ah, that's a good point
r
the preference for members doesn't come into play