Type Inference, Data Types and String

1. Type Inference

What is Type Inference?

Type inference means Kotlin automatically understands the data type from the value.

fun main() {
    val name = "Mahesh"
    val age = 30
    val price = 99.99
    val isActive = true
}

Kotlin understands:

CodeKotlin Understands
val name = "Mahesh"String
val age = 30Int
val price = 99.99Double
val isActive = trueBoolean


With Manual Type

You can also write the data type manually.

fun main() {
    val name: String = "Mahesh"
    val age: Int = 30
    val price: Double = 99.99
    val isActive: Boolean = true
}

Both ways are correct.


Simple Meaning

Kotlin can guess the type automatically.
So we do not always need to write Int, String, Boolean, etc.


2. Basic Data Types

Data type tells Kotlin what kind of value is stored.


Common Data Types

Data TypeUsed ForExample
IntWhole number10, 100, 500
LongVery large number9876543210L
FloatDecimal number4.5f
DoubleMore accurate decimal number99.99
BooleanTrue/false valuetrue, false
CharSingle character'A'
StringText"Mahesh"


Example

fun main() {
    val studentId: Int = 101
    val mobileNumber: Long = 9876543210L
    val percentage: Double = 89.75
    val rating: Float = 4.5f
    val isPassed: Boolean = true
    val grade: Char = 'A'
    val studentName: String = "Mahesh"

    println(studentId)
    println(mobileNumber)
    println(percentage)
    println(rating)
    println(isPassed)
    println(grade)
    println(studentName)
}

Output

101
9876543210
89.75
4.5
true
A
Mahesh


3. String

A String is used to store text.

fun main() {
    val name = "Mahesh"
    val city = "Noida"

    println(name)
    println(city)
}

Output

Mahesh
Noida


4. String Templates

What is String Template?

String template is used to print variables inside a string.

In Kotlin, we use $.


Without String Template

fun main() {
    val name = "Mahesh"
    val age = 30

    println("My name is " + name + " and my age is " + age)
}


With String Template

fun main() {
    val name = "Mahesh"
    val age = 30

    println("My name is $name and my age is $age")
}

Output

My name is Mahesh and my age is 30


String Template with Expression

For calculations or expressions, use `${}`.
fun main() {
    val a = 10
    val b = 20

    println("Sum is ${a + b}")
}

Output

Sum is 30


Real-Life Example

fun main() {
    val studentName = "Mahesh"
    val marks = 85

    println("Student $studentName scored $marks marks.")
}

Output

Student Mahesh scored 85 marks.