Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlin.reflect.full.memberProperties
- import kotlin.reflect.full.primaryConstructor
- import java.net.URLEncoder
- import java.net.URLDecoder
- import java.nio.charset.StandardCharsets
- fun String.encodeToUtf8(): String = URLEncoder.encode(this, StandardCharsets.UTF_8.toString())
- fun String.decodeFromUtf8(): String = URLDecoder.decode(this, StandardCharsets.UTF_8.toString())
- fun Any?.encodedIfPossible(): Any? {
- return when (this) {
- is String -> this.encodeToUtf8()
- is List<*> -> this.map { it.encodedIfPossible() }
- is Set<*> -> this.map { it.encodedIfPossible() }.toSet()
- is Map<*, *> -> this.mapValues { it.value.encodedIfPossible() }
- else -> this?.let { if (it::class.isData) it.encodedStrings() else it }
- }
- }
- fun <T : Any> T.encodedStrings(): T {
- val clazz = this::class
- val constructor = clazz.primaryConstructor
- ?: throw IllegalArgumentException("Class ${clazz.simpleName} must have a primary constructor")
- val args = constructor.parameters.associateWith { param ->
- val property = clazz.memberProperties.firstOrNull { it.name == param.name }
- val value = property?.call(this)
- value.encodedIfPossible()
- }
- return constructor.callBy(args)
- }
- fun Any?.decodedIfPossible(): Any? {
- return when (this) {
- is String -> this.decodeFromUtf8()
- is List<*> -> this.map { it.decodedIfPossible() }
- is Set<*> -> this.map { it.decodedIfPossible() }.toSet()
- is Map<*, *> -> this.mapValues { it.value.decodedIfPossible() }
- else -> this?.let { if (it::class.isData) it.decodedStrings() else it }
- }
- }
- fun <T : Any> T.decodedStrings(): T {
- val clazz = this::class
- val constructor = clazz.primaryConstructor
- ?: throw IllegalArgumentException("Class ${clazz.simpleName} must have a primary constructor")
- val args = constructor.parameters.associateWith { param ->
- val property = clazz.memberProperties.firstOrNull { it.name == param.name }
- val value = property?.call(this)
- value.decodedIfPossible()
- }
- return constructor.callBy(args)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement