Forge Fate
Today I Learned

2026-10-07 Kotlin Basics: Types, Functions, Unit, File Structure, if and when

7 min read

Today I studied Kotlin's basic types, function declarations, Unit, file structure, and if and when. At the time, I compiled the examples and checked their output and error messages.

Alongside the syntax, this article covers these questions:

  • How is a variable's type determined when it is omitted?
  • When do numeric types require an explicit conversion?
  • Does omitting a function's return type always mean Unit?
  • What conditions apply when if and when are used as values?

Environment verified at the time

Kotlin 2.2.20, the kotlinc bundled with IntelliJ IDEA, and JVM 21.

Output and error messages identified as original records come from that earlier practice. Examples reorganized with variable declarations and main, and the added illustration of mixed numeric arithmetic, are distinguished from the exact code executed then.

1. Start with a file to run

Kotlin allows top-level functions without a containing class. A program's entry point can also be a top-level main function. Kotlin basic syntax

The file-structure example used in the original practice was named Basics.kt:

kotlin
package study.basicsimport kotlin.math.maxfun main() {    println(max(3, 7))}

The file begins with package, followed by import. This example prints 7, the larger number.

I compiled and ran it this way at the time:

sh
kotlinc Basics.kt -d outkotlin -cp out study.basics.BasicsKt

Compilation produced:

text
out/study/basics/BasicsKt.class

In this example, the JVM class BasicsKt holds the top-level function. Running it uses the package-qualified name study.basics.BasicsKt.

The default name appends Kt to the filename, but Kotlin also supports specifying another JVM name. Do not generalize this into a claim that every Kotlin file always compiles under that name. JVM representation of Kotlin top-level functions

How to read the code blocks below

The Kotlin code blocks that follow are separate examples. Do not paste the main functions from multiple blocks into one file.

A standalone example can be checked with the following commands. These are execution instructions, not a new execution record.

sh
kotlinc Example.kt -include-runtime -d example.jarjava -jar example.jar

Save one code block in Example.kt. Run the JAR only if compilation succeeds. The kotlinc command must be available in the terminal. Kotlin command-line compiler guide

Examples intended to fail compilation are marked separately. Do not mix them into working examples. Korean strings and comments in the original code are retained so the code and outputs remain consistent; the surrounding prose explains their meaning.

2. Basic types and variables

val and var differ in whether reassignment is allowed

kotlin
fun main() {    val name = "코틀린"    var count = 0    count += 1    println(name)    println(count)}

After initialization, a val variable cannot be assigned another value; a var can. Here, count becomes 1. The name string means “Kotlin” in Korean.

I settled on using val by default and var where reassignment is needed.

val means the variable cannot be reassigned. It does not mean the internal state of the referenced object is always immutable.

Omitting the type does not remove the type

This fragment illustrates type declarations:

kotlin
val i = 42               // Intval l = 3_000_000_000    // Longval l2 = 10L             // Longval d = 3.14             // Doubleval f = 2.5f             // Floatval b = true             // Booleanval c = 'A'              // Charval s = "코틀린"          // Stringval explicit: Int = 42   // 타입을 직접 지정

When the type is omitted, the compiler infers it from the initializer and context. To write it explicitly, put : Type after the name, unlike Java's order.

The recorded type names for the eight values were:

text
Int Long Long Double Float Boolean Char String

For declarations like these, initialized with integer literals and no explicit type, values within the Int range infer Int; values beyond that range but within Long infer Long. A suffix such as 10L can also specify Long.

Underscores improve readability: 3_000_000_000 means three billion. Kotlin numeric types

Numeric assignment requires explicit conversion

This is an independent example intended to fail compilation:

kotlin
fun main() {    val i: Int = 1    val l: Long = i}

Java can assign an int value directly to a long variable, but Kotlin requires explicit conversion for this assignment.

The error recorded for the same assignment issue was:

text
error: initializer type mismatch: expected 'Long', actual 'Int'.

Keep the working version separate:

kotlin
fun main() {    val i: Int = 1    val l: Long = i.toLong()    println(l)}

Use conversion functions such as toLong(), toInt(), and toDouble(). Required types also matter when passing numeric values as function arguments.

Do not extend this rule to mean that all operations involving different numeric types require explicit conversion.

The following illustrative example was added to clarify that distinction:

kotlin
fun main() {    val i: Int = 1    val l: Long = 2L    val sum = i + l    println(sum)              // 예상 출력: 3    println(sum::class.simpleName) // 예상 출력: Long}

Adding an Int and a Long is allowed; this expression produces a Long. The expected output is 3 followed by Long. Distinguish assignment and argument passing from mixed numeric arithmetic. Kotlin mixed numeric expressions

Put variables and expressions in strings

kotlin
fun main() {    val a = 1    val b = 2    println("$a + $b = ${a + b}")}

The output is:

text
1 + 2 = 3

Use $variable for one variable and ${expression} for a calculation.

3. Functions: distinguish declaration from invocation

The basic declaration looks like this:

kotlin
fun add(a: Int, b: Int): Int {    return a + b}
  • Declare a function with fun.
  • Write parameters as name: Type.
  • Put the return type after the parameter list.

If the body is one expression, use an expression body with =:

kotlin
fun multiply(a: Int, b: Int) = a * b

The return type is inferred from a * b, which is Int here.

Default values and named arguments

Adding explicit printing to the original function example gives:

kotlin
fun greet(    name: String,    greeting: String = "안녕"): String = "$greeting, $name!"fun main() {    println(greet("코틀린"))    println(greet(greeting = "Hi", name = "Kim"))}

Its output is:

text
안녕, 코틀린!Hi, Kim!

The first line means “Hello, Kotlin!” The first call omits greeting and uses its default. The second uses argument names to pass them in a different order from the declaration.

greet(...) returns a string; println(...) prints it. In an ordinary program, calling a function does not automatically print its returned string.

Default values reduce the need for separate overloads just to support omitted arguments. Kotlin functions and default arguments

4. Unit: omitting the return type does not always mean the same thing

Functions used for actions such as printing, rather than a distinct result, use the Unit return type.

kotlin
fun printSum(a: Int, b: Int) {    println("$a + $b = ${a + b}")}

This function returns Unit because it has a block body and no explicit return type. It can also be written explicitly:

kotlin
fun printSumExplicit(a: Int, b: Int): Unit {    println("$a + $b = ${a + b}")}

The earlier expression-bodied function is different:

kotlin
fun multiply(a: Int, b: Int) = a * b

Its return type is also omitted, but the expression infers Int.

Function formReturn type
fun f() { ... }Unit when not specified
fun f() = expressionInferred from the expression
fun f(): Int { return ... }The explicitly declared Int

Rather than memorizing “omitting the return type means Unit,” check whether the function has a block body or an expression body. Kotlin function return types

Unit is a type with an actual value

Unit has exactly one value, also called Unit. It plays a role similar to Java's void, but Kotlin allows the value to be received and used.

Combining the original fragments into an independent example gives:

kotlin
fun printSum(a: Int, b: Int) {    println("$a + $b = ${a + b}")}fun main() {    val r = printSum(1, 2)    println(r)    println(r == Unit)}

The output recorded at the time was:

text
1 + 2 = 3kotlin.Unittrue

The first line is printed inside printSum. The second prints the returned Unit value, and the final line compares that value with Unit.

5. if: choose a value using a condition

Kotlin's if can be used as an expression that produces a value.

kotlin
fun maxOf2(a: Int, b: Int): Int =    if (a > b) a else bfun main() {    println(maxOf2(3, 7))}

An if expression can serve the role of Java's condition ? valueIfTrue : valueIfFalse.

The final expression in a block supplies the result

Making the count declaration explicit in the original example gives:

kotlin
fun main() {    val count = 1    val result = if (count > 0) {        println("양수 블록")        "positive"    } else {        "zero or negative"    }    println(result)}

The expected output is:

text
양수 블록positive

The first line means “positive block.” The true branch prints that message first, then uses its final expression, "positive", as the value of result.

The else branch covers negative numbers as well as zero, so its explanatory string has been changed to reflect that range.

An if used for its value needs else

This example is intended to fail compilation:

kotlin
fun main() {    val x = 1    val z = if (x > 0) "p"}

The code tries to assign the if result to z, but supplies no value for a false condition.

The relevant error recorded at the time was:

text
error: 'if' must have both main and 'else' branches when used as an expression.

If the code only performs an action conditionally and does not use a result, it can omit else:

kotlin
fun main() {    val x = 1    if (x > 0) {        println("양수")    }}

This prints the Korean word for “positive.” Not every if requires else; check whether its result value is being used. Kotlin if expressions

6. when: branch by value, range, or type

Use when to handle multiple cases. It resembles Java's switch, but supports ranges and type conditions as well as individual values.

Branches are checked from top to bottom, and a matching branch executes. No break is needed to prevent fall-through.

Values, ranges, and multiple values

kotlin
fun grade(score: Int): String = when (score) {    100 -> "만점"    in 90..99 -> "A"    in 80 until 90 -> "B"    else -> "C 이하"}fun dayType(day: String): String = when (day) {    "토", "일" -> "주말"    else -> "평일"}fun main() {    println(grade(95))    println(dayType("토"))}

The expected output is:

text
A주말

The second line means “weekend.” 90..99 includes both endpoints; 80 until 90 includes 80 but excludes 90.

These functions illustrate branching syntax. They do not validate score ranges or weekday strings. For example, grade routes negative values and values above 100 into else too.

Type checks and smart casts

The original practice used this describe function:

kotlin
fun describe(x: Any): String = when (x) {    1 -> "숫자 1"    "hello" -> "인사"    is Long -> "Long 타입"    !is String -> "문자열이 아님"    else -> "그 밖의 문자열: ${x.length}"}fun main() {    println(describe(1))    println(describe("hello"))    println(describe(5L))    println(describe(2.0))    println(describe("abc"))}

The recorded results of the calls were:

text
숫자 1인사Long 타입문자열이 아님그 밖의 문자열: 3

The lines mean “number 1,” “greeting,” “Long type,” “not a string,” and “other string: 3.”

The parameter's declared type is Any, yet x.length is available in the final branch.

The preceding !is String branch already handles non-string values, so the compiler knows that an x reaching the last branch is a string. Using a more specific type based on such checks is called a smart cast. Kotlin type checks and smart casts

when without a subject

Without a subject after when, write a condition in each branch:

kotlin
fun sign(n: Int): String = when {    n < 0 -> "음수"    n == 0 -> "0"    else -> "양수"}fun main() {    println(sign(-1))    println(sign(0))    println(sign(1))}

The expected output is:

text
음수0양수

These lines mean “negative,” “0,” and “positive.” Read this as an alternative to an if-else if sequence that checks conditions in order.

A when expression must cover every case

This example is intended to fail compilation:

kotlin
fun main() {    val x: Int = 1    val y = when (x) {        1 -> "one"    }}

It tries to assign the value of when to y, but supplies no branch for the other possible Int values.

The error recorded at the time was:

text
error: 'when' expression must be exhaustive. Add an 'else' branch.

For this example, add else:

kotlin
fun main() {    val x: Int = 1    val y = when (x) {        1 -> "one"        else -> "other"    }    println(y)}

The rule is not “every when must have else.” It is that a when whose result value is required must handle all possible cases. Depending on the type, enumerating all required branches can satisfy that condition without else. Exhaustive when expressions

7. Rules summarized from this study

TopicWhat to remember
val and varDistinguish whether a variable can be reassigned.
Type inferenceOmitting the written type still lets the compiler determine it.
Numeric conversionDistinguish assignment and function arguments from mixed numeric arithmetic.
FunctionsDistinguish declaration, returned value, and printed output.
Omitted return typeBlock bodies default to Unit; expression bodies infer from their expression.
UnitA real type with one value.
File structureTop-level functions and main are allowed.
ifRequires else when used for its result value.
whenMust cover all cases when used for its result value.

When running examples, keep successful and failing code separate, and include required variable declarations in failing examples too. That helps distinguish errors from undeclared variables from the syntax error being investigated.

This article covers basic types, functions, and conditional branching. It organizes rules for reading code around the outputs and errors checked at the time.

Report an error or share feedback

Open a draft with this article’s title and URL. Review the message and recipient before sending.

To: [email protected]

Open email draft

If no email app opens, copy these details into your usual email service.

Contact information