Converters.kt

  1. package com.hexagontk.converters

  2. import kotlin.reflect.KClass

  3. /**
  4.  * Utility method to convert one type to another.
  5.  *
  6.  * @param target Target type for the source instance.
  7.  * @receiver Value to convert to another type.
  8.  *
  9.  * @see ConvertersManager.convert
  10.  */
  11. fun <T : Any> Any.convert(target: KClass<T>): T =
  12.     ConvertersManager.convert(this, target)

  13. /**
  14.  * Convert a group of instances of one type to another type.
  15.  *
  16.  * @param target Target type for the source instances in the group.
  17.  * @receiver Value to convert to another type.
  18.  * @return List of converted instances, returns empty list if target is `null`.
  19.  *
  20.  * @see ConvertersManager.convertObjects
  21.  */
  22. fun <T : Any> Iterable<Any>?.convertObjects(target: KClass<T>): List<T> =
  23.     ConvertersManager.convertObjects(this ?: emptyList(), target)

  24. /**
  25.  * Utility method to convert one type to another.
  26.  *
  27.  * @param T Target type for the source instance.
  28.  * @receiver Value to convert to another type.
  29.  *
  30.  * @see ConvertersManager.convert
  31.  */
  32. inline fun <reified T : Any> Any.convert(): T =
  33.     convert(T::class)

  34. /**
  35.  * Convert a group of instances of one type to another type.
  36.  *
  37.  * @param T Target type for the source instances in the group.
  38.  * @receiver Value to convert to another type.
  39.  * @return List of converted instances, returns empty list if target is `null`.
  40.  *
  41.  * @see ConvertersManager.convertObjects
  42.  */
  43. inline fun <reified T : Any> Iterable<Any>?.convertObjects(): List<T> =
  44.     convertObjects(T::class)