or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arguments.mdconfiguration-sources.mdcore-commands.mdexceptions.mdindex.mdoptions.mdparameter-groups.mdparameter-types.mdshell-completion.mdtesting-utilities.md

parameter-types.mddocs/

0

# Parameter Types

1

2

Built-in type converters for common data types including numeric types, enums, choices, and platform-specific types like files and paths.

3

4

## Capabilities

5

6

### Numeric Types

7

8

Convert parameters to numeric types with optional range restrictions.

9

10

```kotlin { .api }

11

/** Convert to Int */

12

fun RawOption.int(): NullableOption<Int, Int>

13

fun RawArgument.int(): ProcessedArgument<Int, Int>

14

15

/** Convert to Long */

16

fun RawOption.long(): NullableOption<Long, Long>

17

fun RawArgument.long(): ProcessedArgument<Long, Long>

18

19

/** Convert to Float */

20

fun RawOption.float(): NullableOption<Float, Float>

21

fun RawArgument.float(): ProcessedArgument<Float, Float>

22

23

/** Convert to Double */

24

fun RawOption.double(): NullableOption<Double, Double>

25

fun RawArgument.double(): ProcessedArgument<Double, Double>

26

27

/** Convert to UInt (unsigned integer) */

28

fun RawOption.uint(): NullableOption<UInt, UInt>

29

fun RawArgument.uint(): ProcessedArgument<UInt, UInt>

30

31

/** Convert to ULong (unsigned long) */

32

fun RawOption.ulong(): NullableOption<ULong, ULong>

33

fun RawArgument.ulong(): ProcessedArgument<ULong, ULong>

34

```

35

36

**Usage Examples:**

37

38

```kotlin

39

class MyCommand : CliktCommand() {

40

// Basic numeric options

41

private val port by option("--port", help = "Port number").int().default(8080)

42

private val timeout by option("--timeout", help = "Timeout in seconds").double()

43

private val maxSize by option("--max-size", help = "Maximum size").ulong()

44

45

// Numeric arguments

46

private val count by argument(name = "COUNT", help = "Number of items").int()

47

private val ratio by argument(name = "RATIO", help = "Ratio value").float()

48

49

override fun run() {

50

echo("Port: $port")

51

echo("Timeout: ${timeout}s")

52

echo("Max size: $maxSize bytes")

53

echo("Count: $count")

54

echo("Ratio: $ratio")

55

}

56

}

57

```

58

59

### Range Restrictions

60

61

Restrict numeric values to specific ranges.

62

63

```kotlin { .api }

64

/**

65

* Restrict numeric value to a specific range

66

* @param range Valid range for the value

67

*/

68

fun <T : Comparable<T>> NullableOption<T, T>.restrictTo(range: ClosedRange<T>): NullableOption<T, T>

69

fun <T : Comparable<T>> ProcessedArgument<T, T>.restrictTo(range: ClosedRange<T>): ProcessedArgument<T, T>

70

```

71

72

**Usage Examples:**

73

74

```kotlin

75

class MyCommand : CliktCommand() {

76

// Port number between 1 and 65535

77

private val port by option("--port", help = "Port number")

78

.int().restrictTo(1..65535).default(8080)

79

80

// Percentage between 0 and 100

81

private val confidence by option("--confidence", help = "Confidence percentage")

82

.double().restrictTo(0.0..100.0)

83

84

// Thread count between 1 and available processors

85

private val threads by argument(name = "THREADS", help = "Number of threads")

86

.int().restrictTo(1..Runtime.getRuntime().availableProcessors())

87

}

88

```

89

90

### Boolean Type

91

92

Convert parameters to boolean values.

93

94

```kotlin { .api }

95

/** Convert to Boolean */

96

fun RawOption.boolean(): NullableOption<Boolean, Boolean>

97

fun RawArgument.boolean(): ProcessedArgument<Boolean, Boolean>

98

```

99

100

**Usage Examples:**

101

102

```kotlin

103

class MyCommand : CliktCommand() {

104

// Boolean option (requires explicit true/false value)

105

private val enableFeature by option("--enable-feature", help = "Enable the feature")

106

.boolean().default(false)

107

108

// Boolean argument

109

private val shouldProcess by argument(name = "PROCESS", help = "Whether to process (true/false)")

110

.boolean()

111

112

override fun run() {

113

echo("Feature enabled: $enableFeature")

114

echo("Should process: $shouldProcess")

115

}

116

}

117

```

118

119

### Enum Types

120

121

Convert parameters to enum values with case-insensitive matching.

122

123

```kotlin { .api }

124

/** Convert to Enum with case-insensitive matching */

125

inline fun <reified T : Enum<T>> RawOption.enum(

126

ignoreCase: Boolean = true,

127

key: (T) -> String = { it.name }

128

): NullableOption<T, T>

129

130

inline fun <reified T : Enum<T>> RawArgument.enum(

131

ignoreCase: Boolean = true,

132

key: (T) -> String = { it.name }

133

): ProcessedArgument<T, T>

134

```

135

136

**Usage Examples:**

137

138

```kotlin

139

class MyCommand : CliktCommand() {

140

enum class LogLevel { DEBUG, INFO, WARN, ERROR }

141

enum class OutputFormat { JSON, XML, YAML, CSV }

142

143

// Enum option with default

144

private val logLevel by option("--log-level", help = "Logging level")

145

.enum<LogLevel>().default(LogLevel.INFO)

146

147

// Enum argument

148

private val format by argument(name = "FORMAT", help = "Output format")

149

.enum<OutputFormat>()

150

151

// Case-sensitive enum

152

private val mode by option("--mode", help = "Processing mode")

153

.enum<ProcessingMode>(ignoreCase = false)

154

155

override fun run() {

156

echo("Log level: $logLevel")

157

echo("Format: $format")

158

echo("Mode: $mode")

159

}

160

}

161

```

162

163

### Choice Types

164

165

Convert parameters to values from predefined choices.

166

167

```kotlin { .api }

168

/** Convert using choice map */

169

fun <T : Any> RawOption.choice(

170

choices: Map<String, T>,

171

metavar: String = choices.keys.joinToString("|", "(", ")"),

172

ignoreCase: Boolean = false

173

): NullableOption<T, T>

174

175

fun <T : Any> RawArgument.choice(

176

choices: Map<String, T>,

177

ignoreCase: Boolean = false

178

): ProcessedArgument<T, T>

179

180

/** Convert using pair choices */

181

fun <T : Any> RawOption.choice(

182

vararg choices: Pair<String, T>,

183

metavar: String = choices.map { it.first }.joinToString("|", "(", ")"),

184

ignoreCase: Boolean = false

185

): NullableOption<T, T>

186

187

fun <T : Any> RawArgument.choice(

188

vararg choices: Pair<String, T>,

189

ignoreCase: Boolean = false

190

): ProcessedArgument<T, T>

191

192

/** Convert using string choices */

193

fun RawOption.choice(

194

vararg choices: String,

195

metavar: String = choices.joinToString("|", "(", ")"),

196

ignoreCase: Boolean = false

197

): NullableOption<String, String>

198

199

fun RawArgument.choice(

200

vararg choices: String,

201

ignoreCase: Boolean = false

202

): ProcessedArgument<String, String>

203

```

204

205

**Usage Examples:**

206

207

```kotlin

208

class MyCommand : CliktCommand() {

209

// String choices

210

private val compression by option("--compression", help = "Compression algorithm")

211

.choice("none", "gzip", "bzip2", "xz").default("none")

212

213

// Choice with custom values

214

private val verbosity by option("-v", "--verbosity", help = "Verbosity level")

215

.choice(mapOf(

216

"quiet" to 0,

217

"normal" to 1,

218

"verbose" to 2,

219

"debug" to 3

220

)).default(1)

221

222

// Case-insensitive choices

223

private val protocol by argument(name = "PROTOCOL", help = "Network protocol")

224

.choice("http", "https", "ftp", "sftp", ignoreCase = true)

225

226

override fun run() {

227

echo("Compression: $compression")

228

echo("Verbosity: $verbosity")

229

echo("Protocol: $protocol")

230

}

231

}

232

```

233

234

### File System Types (JVM Platform)

235

236

Convert parameters to file system objects (available on JVM platform only).

237

238

```kotlin { .api }

239

/** Convert to java.io.File */

240

fun RawOption.file(): NullableOption<File, File>

241

fun RawArgument.file(): ProcessedArgument<File, File>

242

243

/** Convert to java.nio.file.Path */

244

fun RawOption.path(): NullableOption<Path, Path>

245

fun RawArgument.path(): ProcessedArgument<Path, Path>

246

```

247

248

**Usage Examples:**

249

250

```kotlin

251

class MyCommand : CliktCommand() {

252

// File options

253

private val configFile by option("--config", help = "Configuration file")

254

.file().default(File("config.properties"))

255

256

private val outputDir by option("--output-dir", help = "Output directory")

257

.path().default(Paths.get("output"))

258

259

// File arguments

260

private val inputFile by argument(name = "INPUT", help = "Input file to process").file()

261

private val backupPath by argument(name = "BACKUP", help = "Backup location").path()

262

263

override fun run() {

264

echo("Config file: ${configFile.absolutePath}")

265

echo("Output directory: ${outputDir.toAbsolutePath()}")

266

echo("Input file: ${inputFile.name}")

267

echo("Backup path: $backupPath")

268

}

269

}

270

```

271

272

### Stream Types (JVM Platform)

273

274

Convert parameters to input/output streams (available on JVM platform only).

275

276

```kotlin { .api }

277

/** Convert to InputStream */

278

fun RawOption.inputStream(): NullableOption<InputStream, InputStream>

279

fun RawArgument.inputStream(): ProcessedArgument<InputStream, InputStream>

280

281

/** Convert to OutputStream */

282

fun RawOption.outputStream(): NullableOption<OutputStream, OutputStream>

283

fun RawArgument.outputStream(): ProcessedArgument<OutputStream, OutputStream>

284

```

285

286

**Usage Examples:**

287

288

```kotlin

289

class MyCommand : CliktCommand() {

290

// Stream options (stdin/stdout supported with "-")

291

private val input by option("--input", help = "Input stream (use '-' for stdin)")

292

.inputStream().default(System.`in`)

293

294

private val output by option("--output", help = "Output stream (use '-' for stdout)")

295

.outputStream().default(System.out)

296

297

override fun run() {

298

input.use { inputStream ->

299

output.use { outputStream ->

300

inputStream.copyTo(outputStream)

301

}

302

}

303

}

304

}

305

```

306

307

### Custom Type Conversion

308

309

Create custom type converters for domain-specific types.

310

311

```kotlin { .api }

312

/**

313

* Convert using custom conversion function

314

* @param metavar Placeholder for help text

315

* @param conversion Custom conversion function

316

*/

317

fun <T : Any> RawOption.convert(

318

metavar: String,

319

conversion: ValueConverter<String, T>

320

): NullableOption<T, T>

321

322

fun <T : Any> RawArgument.convert(

323

conversion: ArgValueConverter<String, T>

324

): ProcessedArgument<T, T>

325

```

326

327

**Usage Examples:**

328

329

```kotlin

330

import java.time.LocalDate

331

import java.time.LocalDateTime

332

import java.time.format.DateTimeFormatter

333

import java.util.regex.Pattern

334

335

class MyCommand : CliktCommand() {

336

// Date conversion

337

private val startDate by option("--start-date", help = "Start date (YYYY-MM-DD)")

338

.convert("DATE") { LocalDate.parse(it) }

339

340

// DateTime conversion

341

private val timestamp by option("--timestamp", help = "Timestamp (ISO format)")

342

.convert("DATETIME") {

343

LocalDateTime.parse(it, DateTimeFormatter.ISO_LOCAL_DATE_TIME)

344

}

345

346

// URL conversion

347

private val apiEndpoint by option("--api-endpoint", help = "API endpoint URL")

348

.convert("URL") {

349

require(it.startsWith("http")) { "URL must start with http or https" }

350

java.net.URL(it)

351

}

352

353

// Regex pattern conversion

354

private val pattern by argument(name = "PATTERN", help = "Regular expression pattern")

355

.convert { Pattern.compile(it) }

356

357

// Custom data class conversion

358

data class Coordinate(val lat: Double, val lon: Double)

359

360

private val location by option("--location", help = "Location as 'lat,lon'")

361

.convert("LAT,LON") {

362

val parts = it.split(",")

363

require(parts.size == 2) { "Location must be in format 'lat,lon'" }

364

Coordinate(parts[0].toDouble(), parts[1].toDouble())

365

}

366

367

override fun run() {

368

echo("Start date: $startDate")

369

echo("Timestamp: $timestamp")

370

echo("API endpoint: $apiEndpoint")

371

echo("Pattern: ${pattern.pattern()}")

372

echo("Location: $location")

373

}

374

}

375

```

376

377

## Type Conversion Context

378

379

Type conversion functions receive a context object with useful properties and methods.

380

381

```kotlin { .api }

382

/**

383

* Context for option type conversion

384

*/

385

interface OptionTransformContext {

386

val context: Context

387

val option: Option

388

val name: String

389

390

/** Throw conversion error */

391

fun fail(message: String): Nothing

392

}

393

394

/**

395

* Context for argument type conversion

396

*/

397

interface ArgumentTransformContext {

398

val context: Context

399

val argument: Argument

400

val name: String

401

402

/** Throw conversion error */

403

fun fail(message: String): Nothing

404

}

405

```

406

407

**Usage Examples:**

408

409

```kotlin

410

class MyCommand : CliktCommand() {

411

// Using context in conversion

412

private val positiveInt by option("--count", help = "Positive integer")

413

.convert("INT") { value ->

414

val parsed = value.toIntOrNull()

415

?: fail("'$value' is not a valid integer")

416

417

if (parsed <= 0) {

418

fail("Value must be positive, got $parsed")

419

}

420

421

parsed

422

}

423

424

// Access option name in conversion

425

private val percentage by option("--percentage", help = "Percentage value")

426

.convert("PERCENT") { value ->

427

val parsed = value.toDoubleOrNull()

428

?: fail("Option $name requires a number, got '$value'")

429

430

if (parsed !in 0.0..100.0) {

431

fail("Option $name must be between 0 and 100, got $parsed")

432

}

433

434

parsed

435

}

436

}

437

```