Giter Site home page Giter Site logo

square / kotlinpoet Goto Github PK

View Code? Open in Web Editor NEW
3.8K 50.0 279.0 6.05 MB

A Kotlin API for generating .kt source files.

Home Page: https://square.github.io/kotlinpoet/

License: Apache License 2.0

Java 0.61% Kotlin 99.39%
kotlin code-generation javapoet

kotlinpoet's Introduction

KotlinPoet

KotlinPoet is a Kotlin and Java API for generating .kt source files.

License

Copyright 2017 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

kotlinpoet's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kotlinpoet's Issues

object support

Basically the same as class except no constructors allowed

Using @Throws annotation instead of Java throws syntax

I was checking out sources and stumbled upon usage of the invalid in Kotlin throws syntax. Before fixing it I decided to open the issue since it probably will require api changes.
So there are several options:

  • Completely remove addException apis from FunSpec since this syntax is not a part of the language and delegate it to AnnotationSpec

  • Leave current api unchanged and convert supplied exceptions to AnnotationSpec internally

  • Create a new api

What do you think? I would be happy to fix it.

Incorrect array generation for AnnotationSpec params

Example:

@Test fun defaultAnnotation() {
  val name = AnnotationSpecTest.IsAnnotated::class.java.canonicalName
  val element = compilation.elements.getTypeElement(name)
  val annotation = AnnotationSpec.get(element.annotationMirrors[0])

  val taco = TypeSpec.classBuilder("Taco")
      .addAnnotation(annotation)
      .build()
  assertThat(toString(taco)).isEqualTo("""
        |package com.squareup.tacos
        |
        |import com.squareup.kotlinpoet.AnnotationSpecTest
        |import java.lang.Override
        |import kotlin.Double
        |import kotlin.Float
        |
        |@AnnotationSpecTest.HasDefaultsAnnotation(
        |    o = AnnotationSpecTest.Breakfast.PANCAKES,
        |    p = 1701,
        |    f = 11.1,
        |    m = {
        |        9,
        |        8,
        |        1
        |    },
        |    l = Override::class,
        |    j = @AnnotationSpecTest.AnnotationA,
        |    q = @AnnotationSpecTest.AnnotationC("bar"),
        |    r = {
        |        Float::class,
        |        Double::class
        |    }
        |)
        |class Taco
        |""".trimMargin())
}

{} won't work in Kotlin. It has to be arrayOf(), intArrayOf() or something different, hence AnnotationSpec should be aware of the type of the parameter. Would it make sense to capture this info through addMember()?

fun addMember(name: String, type: ClassName, format: String, vararg args: Any)

fun addMember(name: String, type: ClassName, codeBlock: CodeBlock)

Based on the type, and in case there are multiple values for the same name, the builder will be able to generate correct CodeBlock for the array and place it as the first element in the members list.

Please share your thoughts. I might be able to work out a PR this week.

superclass generates "extends" instead of ":"

When specifying a superclass on a class builder, the generated class contains the "extends" keyword instead of ":"

val classBuilder = TypeSpec.Companion.classBuilder("Child")
classBuilder.superclass(TypeName.Companion.get(Parent::class))

Produces :
Child extends Parent

Instead of :
Child: Parent

Emitting redundant modifiers

TypeSpecTest#annotation emits public for the top-level type but this is the default and shouldn't be emitted.

KClass to TypeName broken ?

In 0.2.0, you could get a TypeName from a KClass with this :

TypeName.Companion.get(String::class)

Which enabled one to get a nullable version of it to define a property with type String? for instance :

TypeName.Companion.get(String::class).asNullable()

This doesn't work anymore, and I can't seem to be able to find a replacement for it in the new version (0.3.0) of TypeName.

Maybe I'm doing something wrong or not looking in the right place ?

Cannot add property to companion object

Attempting to add a property to a companion object causes this error:

Exception in thread "main" java.lang.IllegalStateException: cannot add property val ID: kotlin.String = "id" to COMPANION

The exception is being thrown on line 408 of TypeSpec.kt:
check(kind == Kind.CLASS || kind == Kind.ENUM || kind == Kind.ANNOTATION) { "cannot add property $propertySpec to $kind" }

Is this intentional? If it is, I'm not sure how one is meant to add properties to a companion object.

Thanks! Love the library.

Support KotlinJS external classes

In KotlinJS, declaring a class as external makes all members implicitly external.

Currently the implicit modifiers set for members are not dynamic.

Collapse properties into constructor params when present

When a TypeSpec has constructor params that match it's properties, the properties should be collapsed into the constructor parameters.

This

class Foo(val a: String) {
}

Instead of this:

class Foo(a: String) {
  val a: String
}

Add Val + Var to ParameterSpec

Allow us to add parameters to primaryConstructor() which add val/var so we don't have to explicitly add each property on the type itself, or a simple method on the PropertySpec.Builder to specify it goes into primary constructor.

Something like:

addParameter(ParameterSpec.valBuilder(name, valueType)
                                                        .defaultValue(defaultValue) // vals

addParameter(ParameterSpec.varBuilder(name, valueType)
                                                        .defaultValue(defaultValue) // vars

Or

.addProperty(PropertySpec.builder("name", String::class)
            .initializer("name")
            .inPrimaryConstructor()
            .build())

So our outputted code is more concise.

Kind.OBJECT can't add property?

Hi, why do check() when adding a single property while addProperties() not?

0.3.0 TypeSpec.kt line:403
fun addProperties(propertySpecs: Iterable) = apply {
this.propertySpecs += propertySpecs
}

fun addProperty(propertySpec: PropertySpec) = apply {
check(kind == Kind.CLASS || kind == Kind.ENUM || kind == Kind.ANNOTATION) {
"cannot add property $propertySpec to $kind"
}

propertySpecs += propertySpec
}

Type is written as fully qualified when made nullable

The following code:

val stringType = ClassName.run { String::class.asClassName() }
KotlinFile.builder("somePackage", "SomeFile.kt")
        .addProperty(PropertySpec.builder("prop1", stringType).build())
        .addProperty(PropertySpec.builder("prop2", stringType.asNullable()).build())
        .build()
        .toString()

generates:

package somePackage

import kotlin.String

val prop1: String

val prop2: kotlin.String?

The type for prop2 became kotlin.String? rather than String?

IntelliJ can't automatically import TypeName, ClassName etc extensions

This might be an issue in Intellij but this does not work in AS 3.0 or Intellij 2017.1.4:

String::class.asClassName()

It doesn't help importing import com.squareup.kotlinpoet.*, import com.squareup.kotlinpoet.ClassName.* or import com.squareup.kotlinpoet.ClassName.Companion.*

This works however:

ClassName.run { String::class.asClassName() }

Functions with receivers instead of chained builders

In Kotlin DSLs it's a common pattern to provide a factory function taking a function with receiver, which setups the instance being built, so that instead of:

FunSpec.builder("main")
        .addParameter(ArrayTypeName.of(String::class), "args")
        .addStatement("%T(args[0]).greet()", greeterClass)
        .build()

one can write

FunSpec("main") {
    parameter(ArrayTypeName.of(String::class), "args")
    statement("%T(args[0]).greet()", greeterClass))
}

FunSpec has the signature like the following:

fun FunSpec(name: String, init: FunSpec.Builder.() -> Unit): FunSpec = 
    FunSpec.builder(name).apply(init).build()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.