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 Syntax


Certainly! Kotlin syntax is designed to be intuitive and concise. Let's break down some key elements of Kotlin syntax with examples:

1. Variables and Data Types:

Kotlin supports both mutable and immutable variables.

Example

// Immutable variable (cannot be changed)
val name: String = "Alice"

// Mutable variable (can be changed)
var age: Int = 30

2. Functions:

Functions in Kotlin are defined using the fun keyword.

Example

fun add(a: Int, b: Int): Int {
return a + b
}

3. Control Flow:

Kotlin supports if-else statements, similar to many other languages.

Example

val num = 10

if (num > 0) {
println("Positive")
} else {
println("Non-positive")
}

4. Nullable Types and Safe Calls:

Kotlin has built-in null safety features to prevent null pointer exceptions

Example

var name: String? = "John" // Nullable String

// Safe call operator
println("Length: ${name?.length}")

5. Classes and Objects:

Classes are defined using the class keyword in Kotlin.

Example

class Person(val name: String, var age: Int) {
fun speak() {
println("$name is $age years old.")
}
}

6. String Interpolation:

Kotlin allows you to embed variables directly in strings.

Example

val name = "Alice"
val age = 30

println("Name: $name, Age: $age")

7. Loops:

Kotlin supports both for and while loops.

Example

// For loop
for (i in 1..5) {
println(i)
}

// While loop
var count = 0
while (count < 5) {
println("Count: $count")
count++
}

Understanding these basic syntax elements will give you a solid foundation to start writing Kotlin code.

Advertisement





it pathshaala : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java