生成 Kotlin enum 例子

.templates.tpl.js 中添加 handlebars 自定义钩子

// templates 注入 例子。 不能使用 js 高级语法。
// 插件官方说明文档: http://niuhe.zuxing.net/chapter4/section6.html
// handlebars详细例子参考 https://handlebarsjs.com/zh/

handlebars.registerHelper("isInteger", function () {
  return this.type === "integer";
});

handlebars.registerHelper("delimiter", function (fields, index) {
  if(fields && fields.length-1 == index) {
    return ";";
  }
  return ",";
});

template 内容

enum.tpl 需要生成请求和返回以及引用到的文件定义。 you_package 需修改为你的目标包名

package your_package

// Generated by niuhe.idl
// 此文件由 niuhe.idl 自动生成, 请勿手动修改

{{!-- 模板使用到的自定义钩子: isInteger, delimiter }} --}}
 {{#each items}}
 {{#if desc}}
 /** {{desc}} */
 {{/if}}
 {{#if (isInteger)}}
 enum class {{name}}(val value: Int, val desc: String) {
    {{#each fields}}
    /** {{desc}} */
    {{ name }}({{value}}, "{{desc}}"){{delimiter ../fields @index}}
    {{/each}}
    companion object {
        fun fromValue(value: Int): {{name}}? {
            return values().find { it.value == value }
        }
    }
 }
 {{else}}
 enum class {{name}}(val value: String, val desc: String) {
    {{#each fields}}
    /** {{desc}} */
    {{ name }}("{{value}}", "{{value}}"){{delimiter ../fields @index}}
    {{/each}}
    companion object {
        fun fromValue(value: String): {{name}}? {
            return values().find { it.value == value }
        }
    }
 }
 {{/if}}

{{/each}}

.config.json5 参考配置

 {
    templates: [{
      modes: ["api"],
      template: "./templates/kt_enum.tpl",
      type: "enum",
      output: "./output/Enums.kt",
    }]
 }

生成代码例子

niuhe 定义

class StateEnum(ConstGroup):
    '''状态'''
    NORMAL = Item(1, '正常')
    DISABLED = Item(2, '禁用')
class AppEnum(ConstGroup):
    '''应用'''
    WEIXIN = Item("weixin", "微信")
    QYWX = Item("qywx", "企业微信")

kotlin 生成结果

 /** 状态 */
 enum class StateEnum(val value: Int, val desc: String) {
    /** 正常 */
    NORMAL(1, "正常"),
    /** 禁用 */
    DISABLED(2, "禁用");
    companion object {
        fun fromValue(value: Int): StateEnum? {
            return values().find { it.value == value }
        }
    }
 }
 /** 应用 */
 enum class AppEnum(val value: String, val desc: String) {
    /** 微信 */
    WEIXIN("weixin", "微信"),
    /** 企业微信 */
    QYWX("qywx", "企业微信");
    companion object {
        fun fromValue(value: String): AppEnum? {
            return values().find { it.value == value }
        }
    }
 }