Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Get started


Sure! Kotlin is a modern programming language that runs on the Java Virtual Machine (JVM). It's known for its conciseness, safety features, and interoperability with Java. Let's get started with a simple example.

Step 1: Install Kotlin

You can install Kotlin by downloading the Kotlin compiler (kotlinc) and setting it up on your machine. You can find installation instructions on the official Kotlin website.

Step 2: Hello World Example

Let's create a simple "Hello, World!" program in Kotlin.

Example

fun main() {
println("Hello, World!")
}

In Kotlin, fun is used to declare a function. main() is a special function where the program starts execution. println() is used to print text to the console.

Step 3: Run the Program

Save the above code in a file named HelloWorld.kt. Then, navigate to the directory containing the file in your terminal or command prompt and run:

Example

kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
java -jar HelloWorld.jar

This will compile your Kotlin code into a Java bytecode and run it.

Step 4: Variables and Data Types

In Kotlin, you can declare variables using var (mutable) or val (immutable). Kotlin also has type inference, so you don't always have to specify the data type explicitly.

Example

fun main() {
// Mutable variable
var myNumber = 10
println("My number is: $myNumber")

// Immutable variable
val PI = 3.14
println("Value of PI: $PI")
}

Step 5: Control Flow

Kotlin supports typical control flow structures like if, else, when, for, and while.

Example

fun main() {
val number = 10

// If-else statement
if (number > 0) {
println("Number is positive")
} else {
println("Number is non-positive")
}

// When expression (similar to switch-case)
when (number) {
0 -> println("Number is zero")
in 1..9 -> println("Number is between 1 and 9")
else -> println("Number is negative")
}

// For loop
for (i in 1..5) {
println("Count: $i")
}

// While loop
var x = 5
while (x > 0) {
println("Countdown: $x")
x--
}
}

Conclusion

This is just a basic introduction to Kotlin. There's a lot more to explore, including object-oriented programming, functions, lambdas, and more. But hopefully, this gives you a good starting point!

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java