Skip to content
This repository was archived by the owner on Jan 20, 2023. It is now read-only.

Commit 1ad8fc2

Browse files
committed
マップ関数はパラメータの中に有った方が適切だったため修正
1 parent 8bdf9dc commit 1ad8fc2

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/main/kotlin/com/mapk/kmapper/PlainParameterForMap.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package com.mapk.kmapper
22

3+
import com.mapk.core.EnumMapper
34
import kotlin.reflect.KClass
45
import kotlin.reflect.KFunction
56
import kotlin.reflect.KParameter
67
import kotlin.reflect.full.isSubclassOf
8+
import kotlin.reflect.full.isSuperclassOf
79

810
internal class PlainParameterForMap<T : Any> private constructor(val param: KParameter, val clazz: KClass<T>) {
911
val javaClazz: Class<T> by lazy {
@@ -14,6 +16,25 @@ internal class PlainParameterForMap<T : Any> private constructor(val param: KPar
1416
convertersFromConstructors(clazz) + convertersFromStaticMethods(clazz) + convertersFromCompanionObject(clazz)
1517
}
1618

19+
fun <U : Any> mapObject(value: U): Any? {
20+
val valueClazz: KClass<*> = value::class
21+
22+
// パラメータに対してvalueが代入可能(同じもしくは親クラス)であればそのまま用いる
23+
if (clazz.isSuperclassOf(valueClazz)) return value
24+
25+
val converter: KFunction<*>? = getConverter(valueClazz)
26+
27+
return when {
28+
// converterに一致する組み合わせが有れば設定されていればそれを使う
29+
converter != null -> converter.call(value)
30+
// 要求された値がenumかつ元が文字列ならenum mapperでマップ
31+
javaClazz.isEnum && value is String -> EnumMapper.getEnum(javaClazz, value)
32+
// 要求されているパラメータがStringならtoStringする
33+
clazz == String::class -> value.toString()
34+
else -> throw IllegalArgumentException("Can not convert $valueClazz to $clazz")
35+
}
36+
}
37+
1738
// 引数の型がconverterに対して入力可能ならconverterを返す
1839
fun <R : Any> getConverter(input: KClass<out R>): KFunction<T>? =
1940
converters.find { (key, _) -> input.isSubclassOf(key) }?.second

0 commit comments

Comments
 (0)