CLOVIS
06/06/2025, 7:24 PMclass Foo(
val a: Byte,
val b: Byte,
) {
constructor(bytes: ByteArray) : this(bytes[0], bytes[1])
}
The problem with this implementation is that if bytes
is too small, the error message is not perfectly clear, and if it is too big, there is no error message at all. I can add an error message like so:
constructor(bytes: ByteArray) : this(bytes[0], bytes[1]) {
require(bytes.size == 2) { "…" }
}
but that only protects against the case where the array is too large.
How can I add some code that runs before : this(…)
to add the check? The constructor must remain a constructor.Ruckus
06/06/2025, 7:27 PMclass Foo {
val a: Byte,
val b: Byte,
constructor(a: Byte, b: Byte) {
this.a = a
this.b = b
}
constructor(bytes: ByteArray) {
require(bytes.size == 2) { "_" }
this.a = bytes[0]
this.b = bytes[1]
}
}
CLOVIS
06/06/2025, 7:28 PMGleb Minaev
06/06/2025, 7:31 PMclass Foo(
val a: Byte,
val b: Byte,
)
fun Foo(bytes: ByteArray): Foo {
require(bytes.size == 2) { "_" }
return Foo(bytes[0], bytes[1])
}
Youssef Shoaib [MOD]
06/06/2025, 7:33 PMstatic operator fun invoke
which doesn't have any issues with imports or anythingCLOVIS
06/06/2025, 7:33 PMCLOVIS
06/06/2025, 7:34 PMYoussef Shoaib [MOD]
06/06/2025, 7:35 PMstatic
there.Gleb Minaev
06/06/2025, 7:39 PMinvoke
function is usually an antipattern. Fake constructor looks clearer to me. And I think, it has exactly the same compatibility problems as static operator fun invoke
.CLOVIS
06/06/2025, 9:13 PMRuckus
06/07/2025, 3:20 AMclass Foo(
val a: Byte,
val b: Byte,
) {
constructor(bytes: ByteArray) : this(
bytes[0].also {
// do validation here e.g.
require(bytes.size == 2)
},
bytes[1],
)
// Other constructors
}
Youssef Shoaib [MOD]
06/07/2025, 3:26 AMclass Foo(
val a: Byte,
val b: Byte,
) {
constructor(bytes: ByteArray) : this(
kotlin.run { // can't use run IIRC because uninitialized this. Kotlin please fix this
// do validation here e.g.
require(bytes.size == 2)
bytes[0]
},
bytes[1],
)
// Other constructors
}
Klitos Kyriacou
06/09/2025, 10:03 AM