Skip to content

Commit 84d8ffa

Browse files
committed
TypeConversions lesson & examples added
1 parent 86d0d58 commit 84d8ffa

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/TypeConversions.kt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
fun main() {
2+
3+
/*
4+
5+
In Kotlin, a numeric value of one type is not automatically converted to another type even when the other type is larger.
6+
This is different from how Java handles numeric conversions.
7+
8+
Here's a list of functions in Kotlin used for type conversion:
9+
10+
toByte()
11+
toShort()
12+
toInt()
13+
toLong()
14+
toFloat()
15+
toDouble()
16+
toChar()
17+
18+
Note: There is no conversion for Boolean types.
19+
20+
*/
21+
22+
// String Value
23+
val string1: String = "54"
24+
25+
// convert String to Int
26+
val number2: Int = string1.toInt()
27+
28+
// "54"+11 = 5411
29+
println("number1 = ${string1+11}")
30+
31+
// 54 + 11 = 65
32+
println("number2 = ${number2+11}")
33+
34+
35+
// smaller types are NOT implicitly converted to bigger types.
36+
// This means that we cannot assign a value of type Byte to an Int variable without an explicit conversion
37+
38+
/*
39+
val b: Byte = 1 // OK, literals are checked statically
40+
val i: Int = b // Type mismatch. */
41+
42+
}

0 commit comments

Comments
 (0)