![]() ![]() Kotlin helps avoid null pointer exceptions // When you declare a variables type expicitly, by default its value cannot be null var rocks : Int = null // Use the question mark operator to indicate that a variable can be null var rocks : Int? = null // Whe you have complex data types such as a list, var lotsOfFish : List = listOf( null, null) Kotlin supports underscores in numbers val oneMillion = 1_000_000 val socialSecurityNumber = 999_99_9999L val hexBytes = 0xFF_EC_DE_5E val bytes = 0b11010010_01101001_10010100_100100010 // You can speficy long constants in a format that makes sense to you // The type is inferred by Kotlin Nullability ![]() Number types won't implicitly convert to other types, so you can't assign // A short value to a long variable or a byte to an int val b : Byte = 1 val i : Int = b // ERROR Type Mismatch // But you can always assign them by casting like this val i : Int = b.toInt() Eventhough this is very handy, it unfortunately leads to a decrease in performance // We can avoid creating these objets wrappers by not storing numbers in objects // There are two types of variables in Kotlin // Changeable & Unchangeable // var val // With "val" you can assign value only once val aquarium = 1Īquarium = 2 // -> ERROR! cannot be reassigned // You can assign vals val str = "string " val numInt = 1 val numDouble = 1.0 val bool = false // With "var" you can assign a value, and then you can change it var fish = 2įish = 50 // Type is inferred meaning that compiler can figure out the type from the context // Even so the type is inferred, it becomes fixed at compile time, // So you cannot change a type of a varible in kotlin once it's type has been determined.įish = "Bubbles " // ERROR // We can use variables in operations and there is no punctuation at the end var str = 8 var a = 5 Val num : Int = 2 val dob : Double = 2.0 // Both lines do the exact same thing internally Integer x = 42 ![]() ![]() Boxing describes the process of converting a primitive value to an object and unboxing therefore the inverse // All numerical types in Kotlin have a supertype called Number // Store value one in a variable of type Number // It'll need to be placed in an object wrapper // This is called boxing val boxed : Number = 1 ![]()
0 Comments
|