/
ValueClassSupportAndroid.kt
68 lines (61 loc) · 2.02 KB
/
ValueClassSupportAndroid.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package io.mockk
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.internal.KotlinReflectionInternalError
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.jvm.javaField
// TODO this class is copy-pasted and should be de-duplicated
// see https://github.com/mockk/mockk/issues/857
/**
* Underlying property value of a **`value class`** or self.
*
* The type of the return might also be a `value class`!
*/
val <T : Any> T.boxedValue: Any?
@Suppress("UNCHECKED_CAST")
get() = if (!this::class.isValue_safe) {
this
} else {
(this::class as KClass<T>).boxedProperty.get(this)
}
/**
* Underlying property class of a **`value class`** or self.
*
* The returned class might also be a `value class`!
*/
val KClass<*>.boxedClass: KClass<*>
get() = if (!this.isValue_safe) {
this
} else {
this.boxedProperty.returnType.classifier as KClass<*>
}
private val valueClassFieldCache = mutableMapOf<KClass<out Any>, KProperty1<out Any, *>>()
/**
* Underlying property of a **`value class`**.
*
* The underlying property might also be a `value class`!
*/
private val <T : Any> KClass<T>.boxedProperty: KProperty1<T, *>
get() = if (!this.isValue_safe) {
throw UnsupportedOperationException("$this is not a value class")
} else {
@Suppress("UNCHECKED_CAST")
valueClassFieldCache.getOrPut(this) {
// value classes always have exactly one property with a backing field
this.declaredMemberProperties.first { it.javaField != null }.apply { isAccessible = true }
} as KProperty1<T, *>
}
/**
* Returns `true` if calling [KClass.isValue] is safe.
*
* (In some instances [KClass.isValue] can throw an exception.)
*/
private val <T : Any> KClass<T>.isValue_safe: Boolean
get() = try {
this.isValue
} catch (_: UnsupportedOperationException) {
false
} catch (_: KotlinReflectionInternalError) {
false
}