Skip to content

Commit a29f5c6

Browse files
committed
tiny createConverter() refactor so the logic path is a bit clearer
1 parent 2c4f742 commit a29f5c6

File tree

1 file changed

+17
-15
lines changed
  • core/src/main/kotlin/org/jetbrains/kotlinx/dataframe/impl/api

1 file changed

+17
-15
lines changed

core/src/main/kotlin/org/jetbrains/kotlinx/dataframe/impl/api/convert.kt

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ internal fun getConverter(from: KType, to: KType, options: ParserOptions? = null
230230

231231
internal typealias TypeConverter = (Any) -> Any?
232232

233+
private val TypeConverterIdentity: TypeConverter = { it }
234+
233235
internal fun Any.convertTo(type: KType): Any? {
234236
val clazz = javaClass.kotlin
235237
if (clazz.isSubclassOf(type.jvmErasure)) return this
@@ -242,6 +244,7 @@ internal inline fun <T> convert(crossinline converter: (T) -> Any?): TypeConvert
242244

243245
private enum class DummyEnum
244246

247+
@Suppress("UNCHECKED_CAST")
245248
internal fun createConverter(from: KType, to: KType, options: ParserOptions? = null): TypeConverter? {
246249
if (from.arguments.isNotEmpty() || to.arguments.isNotEmpty()) return null
247250
if (from.isMarkedNullable) {
@@ -250,25 +253,24 @@ internal fun createConverter(from: KType, to: KType, options: ParserOptions? = n
250253
}
251254
val fromClass = from.jvmErasure
252255
val toClass = to.jvmErasure
256+
return when {
257+
fromClass == toClass -> TypeConverterIdentity
253258

254-
if (fromClass == toClass) return { it }
255-
256-
if (toClass.isValue) {
257-
val constructor =
258-
toClass.primaryConstructor ?: error("Value type $toClass doesn't have primary constructor")
259-
val underlyingType = constructor.parameters.single().type
260-
val converter = getConverter(from, underlyingType)
261-
?: throw TypeConverterNotFoundException(from, underlyingType, null)
262-
return convert<Any> {
263-
val converted = converter(it)
264-
if (converted == null && !underlyingType.isMarkedNullable) {
265-
throw TypeConversionException(it, from, underlyingType, null)
259+
toClass.isValue -> {
260+
val constructor =
261+
toClass.primaryConstructor ?: error("Value type $toClass doesn't have primary constructor")
262+
val underlyingType = constructor.parameters.single().type
263+
val converter = getConverter(from, underlyingType)
264+
?: throw TypeConverterNotFoundException(from, underlyingType, null)
265+
return convert<Any> {
266+
val converted = converter(it)
267+
if (converted == null && !underlyingType.isMarkedNullable) {
268+
throw TypeConversionException(it, from, underlyingType, null)
269+
}
270+
constructor.call(converted)
266271
}
267-
constructor.call(converted)
268272
}
269-
}
270273

271-
return when {
272274
fromClass == String::class -> {
273275
val parser = Parsers[to.withNullability(false)]
274276
when {

0 commit comments

Comments
 (0)