or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-com-squareup-retrofit2--converter-scalars

A Retrofit Converter for Java's scalar value types

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.squareup.retrofit2/converter-scalars@3.0.x

To install, run

npx @tessl/cli install tessl/maven-com-squareup-retrofit2--converter-scalars@3.0.0

index.mddocs/

Retrofit Scalars Converter

Retrofit Scalars Converter provides automatic conversion between Java scalar types (String, primitives, and their boxed counterparts) and HTTP request/response bodies with text/plain content type. It enables seamless handling of simple scalar values in Retrofit API definitions without requiring custom serialization logic.

Package Information

  • Package Name: converter-scalars
  • Package Type: maven
  • Language: Java
  • Group ID: com.squareup.retrofit2
  • Artifact ID: converter-scalars
  • Installation:
    <dependency>
      <groupId>com.squareup.retrofit2</groupId>
      <artifactId>converter-scalars</artifactId>
      <version>3.0.0</version>
    </dependency>
    Gradle:
    implementation 'com.squareup.retrofit2:converter-scalars:3.0.0'

Core Imports

import retrofit2.converter.scalars.ScalarsConverterFactory;

Basic Usage

import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.Call;

// Create Retrofit instance with ScalarsConverterFactory
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(ScalarsConverterFactory.create())
    .build();

// Define service interface using scalar types
interface ApiService {
    @POST("message")
    Call<String> sendMessage(@Body String message);
    
    @GET("count")
    Call<Integer> getCount();
    
    @POST("status")
    Call<Boolean> updateStatus(@Body Boolean enabled);
}

// Use the service
ApiService service = retrofit.create(ApiService.class);
Call<String> call = service.sendMessage("Hello World");

Architecture

The converter is built around the Retrofit converter factory pattern:

  • Factory Pattern: ScalarsConverterFactory implements Converter.Factory to provide type-specific converters
  • Request Conversion: Single ScalarRequestBodyConverter handles all scalar-to-RequestBody conversions
  • Response Conversion: Individual converters for each scalar type handle ResponseBody-to-scalar conversions
  • Type Safety: Strict type checking with support for both primitive and boxed types
  • Content Type: Uses text/plain; charset=UTF-8 for request bodies

Capabilities

Converter Factory

Creates and manages converters for scalar types in Retrofit.

public final class ScalarsConverterFactory extends Converter.Factory {
    /**
     * Creates a new instance of the converter factory
     * @return ScalarsConverterFactory instance
     */
    public static ScalarsConverterFactory create();
    
    /**
     * Returns a converter for converting objects to RequestBody
     * @param type the type to convert from
     * @param parameterAnnotations annotations on the parameter
     * @param methodAnnotations annotations on the method
     * @param retrofit the Retrofit instance
     * @return Converter instance for supported types, null otherwise
     */
    @Nullable
    public Converter<?, RequestBody> requestBodyConverter(
        Type type,
        Annotation[] parameterAnnotations,
        Annotation[] methodAnnotations,
        Retrofit retrofit
    );
    
    /**
     * Returns a converter for converting ResponseBody to objects
     * @param type the type to convert to
     * @param annotations annotations on the method
     * @param retrofit the Retrofit instance
     * @return Converter instance for supported types, null otherwise
     */
    @Nullable
    public Converter<ResponseBody, ?> responseBodyConverter(
        Type type, 
        Annotation[] annotations, 
        Retrofit retrofit
    );
}

Supported Scalar Types

The converter supports bidirectional conversion for the following Java types:

String Type

  • Type: java.lang.String
  • Request Conversion: Converts String to text/plain RequestBody
  • Response Conversion: Extracts string content from ResponseBody

Boolean Types

  • Types: boolean, java.lang.Boolean
  • Request Conversion: Converts to string representation ("true"/"false")
  • Response Conversion: Parses string using Boolean.valueOf()

Numeric Primitive Types

  • Types: byte/Byte, short/Short, int/Integer, long/Long, float/Float, double/Double
  • Request Conversion: Converts to string representation using String.valueOf()
  • Response Conversion: Parses string using respective wrapper class valueOf() methods

Character Types

  • Types: char, java.lang.Character
  • Request Conversion: Converts character to single-character string
  • Response Conversion: Extracts first character from response body string
  • Error Handling: Throws IOException with message "Expected body of length 1 for Character conversion but was N" if response body length is not exactly 1

Types

// Core Retrofit types used by the converter
import retrofit2.Converter;
import retrofit2.Retrofit;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.MediaType;

// Standard Java types
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.IOException;
import javax.annotation.Nullable;

Error Handling

The converter may throw the following exceptions:

  • IOException: During conversion operations, particularly:
    • Character conversion when response body length is not exactly 1
    • Network or I/O errors when reading response body content
  • NumberFormatException: When parsing numeric types from malformed string content (thrown by wrapper class valueOf() methods)

Usage Examples:

// Handle potential conversion errors
try {
    Call<Integer> call = service.getNumber();
    Response<Integer> response = call.execute();
    if (response.isSuccessful()) {
        Integer value = response.body(); // May be null
    }
} catch (IOException e) {
    // Handle network or conversion errors
}

// Character conversion with error handling
interface CharService {
    @GET("initial")
    Call<Character> getInitial();
}

// This will throw IOException if response is not exactly 1 character
// For example, if API returns "AB" or empty string

Content Type Details

  • Request Bodies: All scalar values are converted to text/plain; charset=UTF-8 RequestBody
  • Response Bodies: Converter accepts any response content type and attempts to parse the body as a string
  • Encoding: UTF-8 encoding is used for all text conversion operations

Integration Patterns

Service Interface Examples:

interface ScalarApiService {
    // String endpoints
    @POST("echo")
    Call<String> echo(@Body String message);
    
    // Boolean endpoints  
    @POST("toggle")
    Call<Boolean> toggle(@Body Boolean state);
    
    // Numeric endpoints
    @GET("temperature")
    Call<Double> getTemperature();
    
    @POST("quantity")
    Call<Void> setQuantity(@Body Integer count);
    
    // Character endpoint
    @GET("grade")
    Call<Character> getGrade();
}

Multiple Converter Integration:

// Use with other converters (order matters)
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(ScalarsConverterFactory.create()) // Scalars first
    .addConverterFactory(GsonConverterFactory.create())    // JSON for complex objects
    .build();