Skip to content

Commit

Permalink
Optimize Unmarshal.createInstance() function
Browse files Browse the repository at this point in the history
  • Loading branch information
lanlinju committed Oct 22, 2024
1 parent d53ca94 commit cf1d6db
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/main/kotlin/com/lanlinju/bencode/Unmarshal.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,15 @@ private fun createInstance(
fields: List<Field>,
dict: Map<String, BObject>
): Any {
val constructor = clazz.kotlin.primaryConstructor
?: throw IllegalArgumentException("Class must have a primary constructor")
val constructor = clazz.kotlin.primaryConstructor ?: error("Class must have a primary constructor")

val args = constructor.parameters.associateWith { param ->
val fieldAnnotation = fields.find { field -> field.name == param.name }
?.getAnnotation(BencodeName::class.java)?.name
val fieldName = fieldAnnotation ?: param.name
?: throw IllegalArgumentException("Constructor parameter must have a name")
val args = constructor.parameters.associateWith { parameter ->
val annotation = fields.find { field -> field.name == parameter.name }?.getAnnotation(BencodeName::class.java)
val fieldName = annotation?.name ?: parameter.name ?: error("Constructor parameter must have a name")

val value = dict[fieldName]
?: throw IllegalArgumentException("Missing value for parameter $fieldName")
val value = dict[fieldName] ?: error("Missing value for parameter $fieldName")

val fieldType = (param.type.classifier as KClass<*>).java
val fieldType = (parameter.type.classifier as KClass<*>).java
if (isListType(fieldType)) return@associateWith emptyList<Any>()

unmarshal(fieldType, value)
Expand Down

0 comments on commit cf1d6db

Please sign in to comment.