Hi, I'm struggling a lot to generate Kotlin code f...
# getting-started
a
Hi, I'm struggling a lot to generate Kotlin code from a certain pattern of items. Here is a snippet the pattern :
Copy code
ambient/cave/cave7
ambient/cave/cave8
ambient/cave/cave9
ambient/nether/basalt_deltas/ambience
ambient/nether/basalt_deltas/basaltground1
ambient/nether/basalt_deltas/basaltground2
And I need to generate something like this for this pattern :
Copy code
sealed interface Sounds : Argument.Sound {
    override val namespace = "minecraft"

    object Ambiant {
        @Serializable(with = Cave.Companion.CaveSerializer::class)
        enum class Cave : Sounds {
            CAVE7,
            CAVE8,
            CAVE9;

            override fun asString() = "$namespace:ambiant/cave/${name.lowercase()}"

            companion object {
                val values = values()

                object CaveSerializer LowercaseSerializer<Cave>(values)
            }
        }
    }

    ...
}
The deep level can varies from 1 to 3 (
a/b
to
a/b/c/d/e
) and I need the serialization thing, and especially the
asString()
method. For now I have something kinda working but it's made mainly by hand and customized for each files I have with this pattern instead of having a main builder that I use for each ones.
e
doesn't seem that hard. this prints out
Copy code
public object ambient {
  public enum class cave {
    cave7,
    cave8,
    cave9,
  }

  public object nether {
    public enum class basalt_deltas {
      ambience,
      basaltground1,
      basaltground2,
    }
  }
}
and of course you can customize it more
a
Ah I didn't knew there was a library to generate Kotlin code :o I have done similar methods by hand past this
e
if you have kotlinpoet questions you can check #squarelibraries (but if you've used javapoet before it should feel pretty familiar)
🙏 2
generating by hand is just more boilerplate though
e.g. this prints
Copy code
object ambient {
  enum class cave {
    cave7, cave8, cave9;
  }
  object nether {
    enum class basalt_deltas {
      ambience, basaltground1, basaltground2;
    }
  }
}
even if it's more verbose, I'd still prefer kotlinpoet though. it handles all sorts of stuff for you, like imports, string escaping, checking valid names, etc.
a
Yeah I'll change my generation module to use KotlinPoet