Embed Directive in Kotlin

Here’s the translation of the Go code to Kotlin, with explanations in Markdown format suitable for Hugo:

In Kotlin, we don’t have a direct equivalent to the embed directive. However, we can achieve similar functionality using resource files and the ClassLoader. Here’s how we can implement a similar concept:

import java.io.File

// In Kotlin, we use the `object` keyword to declare a singleton
object ResourceReader {
    // This function reads a file from resources as a String
    fun readFileAsString(fileName: String): String =
        this::class.java.getResource(fileName)?.readText() ?: ""

    // This function reads a file from resources as ByteArray
    fun readFileAsBytes(fileName: String): ByteArray =
        this::class.java.getResource(fileName)?.readBytes() ?: ByteArray(0)

    // This function lists all files in a directory in resources
    fun listFiles(dirName: String): List<String> =
        this::class.java.getResource(dirName)?.let { url ->
            File(url.toURI()).listFiles()?.map { it.name } ?: emptyList()
        } ?: emptyList()
}

fun main() {
    // Print out the contents of 'single_file.txt'
    println(ResourceReader.readFileAsString("/folder/single_file.txt"))
    println(ResourceReader.readFileAsBytes("/folder/single_file.txt").toString(Charsets.UTF_8))

    // Retrieve some files from the embedded folder
    val files = ResourceReader.listFiles("/folder")
    files.filter { it.endsWith(".hash") }.forEach { fileName ->
        println(ResourceReader.readFileAsString("/folder/$fileName"))
    }
}

In this Kotlin version:

  1. We create a ResourceReader object (Kotlin’s equivalent of a singleton) that provides methods to read files from resources.

  2. readFileAsString and readFileAsBytes methods read a file from resources as a String or ByteArray respectively.

  3. listFiles method lists all files in a specified directory in resources.

  4. In the main function, we demonstrate how to use these methods to read files and list directory contents.

To use this code:

  1. Create a resources folder in your project.
  2. Inside resources, create a folder directory.
  3. Add single_file.txt, file1.hash, and file2.hash to the folder directory with the appropriate contents.

When you run this program, it will print the contents of single_file.txt twice (once as a String and once as a ByteArray converted to a String), followed by the contents of file1.hash and file2.hash.

Note that this approach reads files at runtime, not compile-time like Go’s embed directive. For compile-time embedding in Kotlin, you might need to use a build tool plugin or code generation.