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:
| Code | Kotlin Understands |
|---|---|
val name = "Mahesh" | String |
val age = 30 | Int |
val price = 99.99 | Double |
val isActive = true | Boolean |
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 Type | Used For | Example |
|---|---|---|
Int | Whole number | 10, 100, 500 |
Long | Very large number | 9876543210L |
Float | Decimal number | 4.5f |
Double | More accurate decimal number | 99.99 |
Boolean | True/false value | true, false |
Char | Single character | 'A' |
String | Text | "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
Mahesh3. String
A String is used to store text.
fun main() {
val name = "Mahesh"
val city = "Noida"
println(name)
println(city)
}Output
Mahesh
Noida4. 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 30String Template with Expression
For calculations or expressions, use `${}`.fun main() {
val a = 10
val b = 20
println("Sum is ${a + b}")
}Output
Sum is 30Real-Life Example
fun main() {
val studentName = "Mahesh"
val marks = 85
println("Student $studentName scored $marks marks.")
}Output
Student Mahesh scored 85 marks.