shouldnt it be bad practice to do validation insid...
# announcements
a
shouldnt it be bad practice to do validation inside the constructor of a data class, when u can just use the copy method to create another “valid” object ? My best idea to solve it so far is to wrap a data class inside a normal class, to avoid the copy method, but still have the benefit of data classes
d
copy
still calls your constructor.
Copy code
data class TestClass(val foo: Int) {
    init {
        require(foo > 5)
    }
}

fun main() {
    println(TestClass(10).copy(foo = 3))
}
Throws an exception.
😮 1
a
aaah good to know, thx !
d
As a general rule of thumb: There won't be any instances of your class where the constructor is not called (exceptions: Java serialization, but never use that mess).