fix: handle option types and nulls properly

This commit is contained in:
Sculas 2022-09-08 11:29:06 +02:00
parent 1d989abd55
commit aff4968e6f
No known key found for this signature in database
GPG key ID: 1530BFF96D1EEB89
3 changed files with 24 additions and 2 deletions

View file

@ -81,6 +81,12 @@ sealed class PatchOption<T>(
val validator: (T?) -> Boolean val validator: (T?) -> Boolean
) { ) {
var value: T? = default var value: T? = default
get() {
if (field == null && required) {
throw RequirementNotMetException
}
return field
}
set(value) { set(value) {
if (value == null && required) { if (value == null && required) {
throw RequirementNotMetException throw RequirementNotMetException
@ -95,7 +101,11 @@ sealed class PatchOption<T>(
* Gets the value of the option. * Gets the value of the option.
* Please note that using the wrong value type results in a runtime error. * Please note that using the wrong value type results in a runtime error.
*/ */
operator fun <T> getValue(thisRef: Any?, property: KProperty<*>) = value as T inline operator fun <reified V> getValue(thisRef: Any?, property: KProperty<*>) =
value as? V ?: throw InvalidTypeException(
V::class.java.canonicalName,
value?.let { it::class.java.canonicalName } ?: "null"
)
/** /**
* Gets the value of the option. * Gets the value of the option.

View file

@ -85,9 +85,16 @@ internal class PatchOptionsTest {
} }
@Test @Test
fun `should fail because of the requirement is not met`() { fun `should fail because the requirement is not met`() {
assertThrows<RequirementNotMetException> { assertThrows<RequirementNotMetException> {
options.nullify("key1") options.nullify("key1")
} }
} }
@Test
fun `should fail because getting a non-initialized option is illegal`() {
assertThrows<RequirementNotMetException> {
println(options["key6"].value)
}
}
} }

View file

@ -196,5 +196,10 @@ class ExampleBytecodePatch : BytecodePatch(listOf(ExampleFingerprint)) {
"key5", File("test.txt").toPath(), "title", "description" "key5", File("test.txt").toPath(), "title", "description"
) )
) )
private var key6: String by option(
PatchOption.StringOption(
"key6", null, "title", "description", true
)
)
} }
} }