Is there a programmatic Kotlin API for formatting ...
# random
a
Is there a programmatic Kotlin API for formatting Kotlin code in runtime? what i am looking for String -> Formatted string Asked perplexity and the AIs but i think it they hallucinate. they say ktlint and ktmt has an api but on their repo i see they have gradle plugins to format your code in build time
h
What do you mean with runtime? Do you want to format a input string of (non compiled) kotlin? ktlint/and other tools don’t care about runtime vs build time, the tools just format a string. Ktlint contains of many module, the Gradle plugin is only one entrypoint. You need the cli entrypoint. But I am not sure, if your (rare) use-case will be supported, eg maybe you need to write it to a file first or need to pull compiler dependencies depending on the tool.
a
> What do you mean with runtime I have a kotlin app that generates kotlin code. I want the code to be formatted and I don't want to write any formatting logic on my own
Copy code
val formattedCode = formatKotlinCode(generatedKotlinCode)
h
What do you/the user do with the generated code? Formatting code is not trivial, you need a lexer and a parser to built a concrete syntax tree, the internal representation of the file that contains the position of the elements in the source code. After parsing, you need to do the formatting and rewrite the source code based on the positions. ktlint uses the kotlin compiler to parse the tree and uses PSI (the internal representation) to rewrite the input. ktlint provides an cli module that you can call (or the classes directly). But it is JVM only and mostly requires real
java.io.File
s.
a
so no. what i am asking does not exist
h
Well, it partly exists, the tests of ktlint "just" format a String: https://github.com/pinterest/ktlint/blob/7d56c831865acdad047132f4ca77facd23f487ec/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/AnnotationRuleTest.kt#L153 But AFAIK, you do need to do the setup (dependencies, files + calling the methods) by yourself.
How do you generate your Kotlin code? It might be easier to change your generator or use a library, like kotlinpoet that provides kind of formatted code.
☝️ 1
☝🏼 1
a
doing code gen manually. not interested in using a lib for it thanks for mentioning kotlinpoet. with a quick look i see they have some code formatting code. might take it from there