Variable

The bridge between ParameterSpec and PropertySpec.

The goal of Variable

ParameterSpec and PropertySpec are very similar:

ParameterSpec

PropertySpec

name

name

modifiers

modifiers

type

type

defaultValue

initializer

null

mutable: Boolean

Although they have more fields, these are the ones KotlinPoetDSL supports before V0.2.

Because they are this similar it would make sense to pass around a type that has the commonalities of both the classes. In KotlinPoetDSL, this class is called Variable.

Constructions

There are 3 function-names: of, valOf, varOf. These can all be invoked the same way. Therefor I show below only using valOf.

val clazz = ClassName("", "Clazz")

"a" valOf String::class // val a : String
"a" valOf clazz //val  a: Clazz

// S surrounds string with quotes
"a".valOf<String>("Hi %L".S(), "you") // val a : String = "Hi you"
"a".valOf(clazz, "%T()", clazz)      // a: Clazz = Clazz()

 // will be supported in V0.2
//"a".valOf(String::class, "Hi %L", "you") // val a : String = "Hi you"

for the vararg:

"a" vararg String::class //vararg a  : String
"a" vararg clazz // vararg a : Clazz

  // will be supported in V0.2 for varargVal and varargVar
 //  "a" varargVal String::class //vararg a : String
//   "a" varargVal clazz        // vararg a : Clazz

Interoperability

Slightly interoperable, but will be improved in V0.2

Creating Variables

val param = ParameterSpec
    .builder("hi", String::class, KModifier.PUBLIC, KModifier.OPEN)
    .defaultValue("hello".S())
    .build()
    .toVariable()
param //public open hi: String = "hello"


val prop = PropertySpec.builder("hi", String::class, KModifier.OPEN)
    .initializer("hello".S())
    .build()
prop // open val hi : String: "hello"

Using Variable

In V0.1 the variables can't be used. In V0.2, the variables can be used interchangeable with ParamSpec and PropertySpec.

Getting KotlinPoetTypes

val t = ("f" varOf String::class)
t.toPropertySpec() // var f : String
t.toParamSpec()   // f : String

Last updated

Was this helpful?