CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-utils-jvm

Ktor utilities library for JVM platform containing common utility functions, cryptographic operations, date handling, logging utilities, pipeline functionality, I/O adapters, encoding/decoding utilities, network address handling, and various platform-specific implementations for the Ktor framework.

Pending
Overview
Eval results
Files

conversion.mddocs/

Data Conversion

Data conversion service for serializing and deserializing types to/from string lists. Provides type-safe conversion with support for custom converters and built-in primitive type handling.

Capabilities

ConversionService Interface

Base interface for data conversion operations between values and string lists.

/**
 * Data conversion service that does serialization and deserialization to/from list of strings
 */
interface ConversionService {
    /** Deserialize values to an instance of type */
    fun fromValues(values: List<String>, type: TypeInfo): Any?
    
    /** Serialize a value to values list */
    fun toValues(value: Any?): List<String>
}

Usage Examples:

import io.ktor.util.converters.*
import io.ktor.util.reflect.*

// Use default conversion service
val service: ConversionService = DefaultConversionService

// Convert from strings to values
val intValue = service.fromValues(listOf("42"), typeInfo<Int>()) as Int
val stringList = service.fromValues(listOf("hello", "world"), typeInfo<List<String>>()) as List<String>

// Convert values to strings
val intStrings = service.toValues(42) // ["42"]
val listStrings = service.toValues(listOf("hello", "world")) // ["hello", "world"]

DefaultConversionService

Built-in conversion service supporting primitive types, collections, and platform-specific conversions.

/**
 * The default conversion service that supports only basic types and enums
 */
object DefaultConversionService : ConversionService {
    override fun fromValues(values: List<String>, type: TypeInfo): Any?
    override fun toValues(value: Any?): List<String>
    
    /** Convert single string value to specific type */
    fun fromValue(value: String, klass: KClass<*>): Any
}

Supported Types:

  • Primitive types: Int, Float, Double, Long, Short, Char, Boolean, String
  • Collections: List<T>, MutableList<T> where T is a supported type
  • Iterable types for serialization
  • Platform-specific types via expect/actual pattern

Usage Examples:

import io.ktor.util.converters.*
import io.ktor.util.reflect.*

// Basic type conversions
val intValue = DefaultConversionService.fromValue("42", Int::class) // 42
val boolValue = DefaultConversionService.fromValue("true", Boolean::class) // true
val floatValue = DefaultConversionService.fromValue("3.14", Float::class) // 3.14f

// List conversions
val numbers = DefaultConversionService.fromValues(
    listOf("1", "2", "3"), 
    typeInfo<List<Int>>()
) as List<Int> // [1, 2, 3]

// Serialization
val intStrings = DefaultConversionService.toValues(123) // ["123"]
val listStrings = DefaultConversionService.toValues(listOf(1, 2, 3)) // ["1", "2", "3"]

DataConversion Class

Configurable conversion service with support for custom type converters.

/**
 * Data conversion plugin to serialize and deserialize types using converters registry
 */
class DataConversion(configuration: Configuration) : ConversionService {
    override fun fromValues(values: List<String>, type: TypeInfo): Any?
    override fun toValues(value: Any?): List<String>
    
    /**
     * Data conversion service configuration
     */
    class Configuration {
        /** Register a converter for type */
        fun convert(type: KClass<*>, convertor: ConversionService)
        
        /** Register and configure converter for type */
        fun <T : Any> convert(type: KType, configure: DelegatingConversionService.Configuration<T>.() -> Unit)
        
        /** Register and configure converter for reified type */
        inline fun <reified T : Any> convert(
            noinline configure: DelegatingConversionService.Configuration<T>.() -> Unit
        )
    }
}

Usage Examples:

import io.ktor.util.converters.*
import java.time.LocalDate
import java.time.format.DateTimeFormatter

// Configure data conversion with custom converters
val dataConversion = DataConversion(DataConversion.Configuration().apply {
    // Register converter for LocalDate
    convert<LocalDate> {
        decode { values -> 
            LocalDate.parse(values.single(), DateTimeFormatter.ISO_LOCAL_DATE)
        }
        encode { value ->
            listOf(value.format(DateTimeFormatter.ISO_LOCAL_DATE))
        }
    }
    
    // Register converter for custom class
    convert<User> {
        decode { values ->
            val parts = values.single().split(":")
            User(parts[0], parts[1].toInt())
        }
        encode { user ->
            listOf("${user.name}:${user.age}")
        }
    }
})

// Use configured conversion
data class User(val name: String, val age: Int)

val user = User("Alice", 30)
val serialized = dataConversion.toValues(user) // ["Alice:30"]
val deserialized = dataConversion.fromValues(serialized, typeInfo<User>()) as User

DelegatingConversionService

Implementation that delegates conversion operations to custom encoder/decoder functions.

/**
 * Implementation of ConversionService that delegates fromValues and toValues to decoder and encoder
 */
class DelegatingConversionService(
    private val klass: KClass<*>,
    private val decoder: ((values: List<String>) -> Any?)?,
    private val encoder: ((value: Any?) -> List<String>)?,
) : ConversionService {
    
    override fun fromValues(values: List<String>, type: TypeInfo): Any?
    override fun toValues(value: Any?): List<String>
    
    /**
     * Custom converter builder to be used in DataConversion.Configuration
     */
    class Configuration<T : Any> {
        /** Configure decoder function */
        fun decode(converter: (values: List<String>) -> T)
        
        /** Configure encoder function */
        fun encode(converter: (value: T) -> List<String>)
    }
}

Usage Examples:

import io.ktor.util.converters.*
import java.util.UUID

// Create custom delegating service for UUID
val uuidService = DelegatingConversionService(
    klass = UUID::class,
    decoder = { values -> UUID.fromString(values.single()) },
    encoder = { value -> listOf(value.toString()) }
)

// Use the service
val uuid = UUID.randomUUID()
val serialized = uuidService.toValues(uuid) // [uuid string]
val deserialized = uuidService.fromValues(serialized, typeInfo<UUID>()) as UUID

Exception Handling

/**
 * Thrown when failed to convert value
 */
open class DataConversionException(message: String = "Invalid data format") : Exception

Usage Examples:

import io.ktor.util.converters.*

try {
    // This will throw DataConversionException for unsupported types
    DefaultConversionService.fromValue("invalid", CustomClass::class)
} catch (e: DataConversionException) {
    println("Conversion failed: ${e.message}")
}

try {
    // This will throw for invalid format
    DefaultConversionService.fromValue("not-a-number", Int::class)
} catch (e: NumberFormatException) {
    println("Invalid number format: ${e.message}")
}

Implementation Notes

  • Platform Support: ConversionService interface is available on all platforms (Common)
  • Expect/Actual Pattern: Platform-specific converters are handled via expect/actual functions
  • Type Safety: Uses TypeInfo and reflection for type-safe conversions
  • Extensibility: Supports custom converters through DataConversion configuration
  • Built-in Types: DefaultConversionService handles all Kotlin primitive types and basic collections
  • Error Handling: Throws DataConversionException for unsupported types and conversion failures

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-utils-jvm

docs

attributes.md

collections.md

compression.md

conversion.md

crypto.md

datetime.md

index.md

io.md

logging.md

pipeline.md

strings.md

tile.json