Structs in Kotlin

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This person struct type has name and age fields:

data class Person(val name: String, var age: Int)

fun newPerson(name: String): Person {
    val p = Person(name, 42)
    return p
}

fun main() {
    println(Person("Bob", 20))                 // This syntax creates a new struct.
    println(Person(name = "Alice", age = 30))  // You can name the fields when initializing a struct.
    println(Person(name = "Fred", age = 0))    // Omitted fields will be zero-valued.
    
    println(Person("Ann", 40))                 // An "&" prefix yields a pointer to the struct.
    println(newPerson("Jon"))                  // It’s idiomatic to encapsulate new struct creation in constructor functions.

    val s = Person(name = "Sean", age = 50)
    println(s.name)                            // Access struct fields with a dot.
    
    val sp = s
    println(sp.age)                            // You can also use dots with struct pointers - the pointers are automatically dereferenced.

    sp.age = 51                                // Structs are mutable.
    println(sp.age)

    val dog = object {
        val name: String = "Rex"
        val isGood: Boolean = true
    }                                          // If a struct type is only used for a single value, we don’t have to give it a name.
    println("${dog.name}, isGood: ${dog.isGood}")
}

To run the Kotlin code, simply use kotlinc to compile the code, followed by kotlin to execute it:

$ kotlinc Person.kt -include-runtime -d Person.jar
$ kotlin Person.jar
Person(name=Bob, age=20)
Person(name=Alice, age=30)
Person(name=Fred, age=0)
Person(name=Ann, age=40)
Person(name=Jon, age=42)
Sean
50
51
Rex, isGood: true

Now that we can run and build basic Kotlin programs, let’s learn more about the language.