Skip to content

Commit

Permalink
Fix InstantiationError when using any() where a sealed type is expected
Browse files Browse the repository at this point in the history
  • Loading branch information
cliffred committed Oct 4, 2022
1 parent 21488e5 commit a28b497
Showing 1 changed file with 27 additions and 17 deletions.
Expand Up @@ -24,24 +24,34 @@ class JvmSignatureValueGenerator(val rnd: Random) : SignatureValueGenerator {
return constructor.call(valueSig)
}

return cls.cast(
when (cls) {
java.lang.Boolean::class -> rnd.nextBoolean()
java.lang.Byte::class -> rnd.nextInt().toByte()
java.lang.Short::class -> rnd.nextInt().toShort()
java.lang.Character::class -> rnd.nextInt().toChar()
java.lang.Integer::class -> rnd.nextInt()
java.lang.Long::class -> rnd.nextLong()
java.lang.Float::class -> rnd.nextFloat()
java.lang.Double::class -> rnd.nextDouble()
java.lang.String::class -> rnd.nextLong().toString(16)
return cls.cast(instantiate(cls, anyValueGeneratorProvider, instantiator))
}

private fun <T : Any> instantiate(
cls: KClass<T>,
anyValueGeneratorProvider: () -> AnyValueGenerator,
instantiator: AbstractInstantiator
): Any = when (cls) {
Boolean::class -> rnd.nextBoolean()
Byte::class -> rnd.nextInt().toByte()
Short::class -> rnd.nextInt().toShort()
Character::class -> rnd.nextInt().toChar()
Integer::class -> rnd.nextInt()
Long::class -> rnd.nextLong()
Float::class -> rnd.nextFloat()
Double::class -> rnd.nextDouble()
String::class -> rnd.nextLong().toString(16)

else ->
@Suppress("UNCHECKED_CAST")
anyValueGeneratorProvider().anyValue(cls, isNullable = false) {
instantiator.instantiate(cls)
} as T
else ->
if (cls.isSealed) {
cls.sealedSubclasses.firstNotNullOfOrNull {
instantiate(it, anyValueGeneratorProvider, instantiator)
} ?: error("Unable to create proxy for sealed class $cls, available subclasses: ${cls.sealedSubclasses}")
} else {
@Suppress("UNCHECKED_CAST")
anyValueGeneratorProvider().anyValue(cls, isNullable = false) {
instantiator.instantiate(cls)
} as T
}
)
}
}

0 comments on commit a28b497

Please sign in to comment.