Udomomo
11/27/2022, 1:24 PMcopy
method not visible from outside.
Many people provide workarounds and I found this. Seems interesting but I don’t know how it works. This uses sealed class and seems hashCode
equals
toString
method of data class can be still used from outside, while copy
method is not. Why only copy
method is hidden by this way?
// Original data class with private constructor
data class User private constructor(val name: String, val id: Int){
companion object{
fun of(name:String, id: Int): User{
return User(if(name.isEmpty()) "Unknown" else name, id)
}
}
}
// Workaround with sealed class
sealed class User {
companion object {
fun of(name: String, id: Int): User = UserData(if (name.isEmpty()) "Unknown" else name, id)
}
abstract val name: String
abstract val id: Int
private data class UserData(override val name: String, override val id: Int) : User()
}
ephemient
11/27/2022, 1:38 PMephemient
11/27/2022, 1:40 PMUdomomo
11/28/2022, 12:58 AMbecause the data class is private, its methods (such as copy) are not accessibleSo
equals
and hashCode
in this case don’t belong to data class too?ephemient
11/28/2022, 1:18 AMAny
, which every type inheritsephemient
11/28/2022, 1:19 AMval name: String
and val id: Int
on the sealed class
in the example you pasted above, so those are available even if the implementation is hiddenephemient
11/28/2022, 1:20 AMcopy
only exists on the data class
which isn't accessible, so the method isn't accessible eitherephemient
11/28/2022, 1:22 AMsealed class
+ private
impl is an easy hack but it has its failings (e.g. toString
uses the wrong name, component1
etc. functions aren't accessible meaning no destructuring)ephemient
11/28/2022, 1:31 AMcopy
, I would either manually write the POJO
class User private constructor(val name: String, val id: Int) {
override fun equals(other: Any?): Boolean = other is User && name == other.name && id == other.id
override fun hashCode(): Int = name.hashCode() * 31 + int.hashCode()
override fun toString(): String = "User(name=$name, id=$id)"
operator fun component1(): String = name
operator fun component2(): Int = id
companion object {
fun of(name: String, id: Int): User = User(name.ifEmpty { "Unknown" }, id)
}
}
or use one of the plugins I mentioned previouslyUdomomo
11/29/2022, 2:03 PMthey are methods ofOh That’s what I overlooked. Thanks!, which every type inheritsAny