Kotlin has three different file extensions that you can use to write Kotlin code:
.kt
extension.kts
extension or Kotlin script.ktm
extension or Kotlin module
This tutorial will help you learn about the three extensions above.
Kotlin .kt file extension
The .kt
extension is the most common Kotlin file extension that’s used to write Kotlin source code.
This extension is used extensively when you’re writing the code for your Android application.
A collection of .kt
files need a main
function as the entry point of the Kotlin application:
fun main() {
println("Hello world!")
}
In Android, this main
function is replaced with the MainActivity
class, which is generated by Android Studio when you create a new application:
package com.example.kotlinbasic
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Without a main
function or the MainActivity
class, Kotlin will throw an error during runtime, saying Function 'main' not found
or Default Activity not found
.
When you’re writing code for an Android or Kotlin application, you need to use the .kt
extension.
Kotlin .kts file extension
The .kts
extension is also known as the Kotlin script extension.
This file extension allows you to run Kotlin code without compilation. The code inside the .kts
file will be executed line by line.
To run a .kts
file, you need to run the kotlinc
command with the -script
option:
kotlinc -script <filename>.kts
The .kts
file is commonly used in Android Studio when you create a Kotlin scratch file.
Inside a .kts
file, Android Studio can execute your Kotlin code without compiling your entire Android application code.
Kotlin .ktm file extension
The .ktm
extension is also known as the Kotlin module extension.
This extension is quite mysterious because I never see it being used anywhere.
For example, I tried to search the kotless
library for the use of .ktm
extension, but can’t find it anywhere.
Take a look at the following screenshot:
But I can find .kts
files in the same library as shown below:
It seems that all open-source Kotlin libraries only used .kt
file for their library source code, so this file extension may not be used anymore.
Now you’ve learned about the file extensions that are available for the Kotlin language. Nice work! 👍