Skip to content

Instantly share code, notes, and snippets.

@alexbezhan
Created May 6, 2020 12:06
Show Gist options
  • Save alexbezhan/d37f604d5f39bc423bde27dd967e50d8 to your computer and use it in GitHub Desktop.
Save alexbezhan/d37f604d5f39bc423bde27dd967e50d8 to your computer and use it in GitHub Desktop.
/**
* Lookup property in obj[path]
* @return found property in a nested object
*/
fun findNestedProperty(obj: Any, path: List<String>): NestedPropertyLookup {
var instance: Any = obj
for (keyIdx in path.indices) {
val memberProperties = instance::class.memberProperties
val property = memberProperties.find { callable ->
callable.name == path[keyIdx]
}
if (property != null) {
val isPathEnd = keyIdx == path.size - 1
if (isPathEnd) {
return NestedPropertyLookup(instance, property)
} else {
instance = property.call(instance) ?: return NestedPropertyLookup(instance, null)
}
} else {
throw GoalbotException("Property ${path[keyIdx]} not found in ${instance::class.qualifiedName}")
}
}
return NestedPropertyLookup(instance, null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment