Vals and Vars
val myname = "kotlin"
var name = "kotlin"
val name = "kotlin"
A read only variable does not mean the instance itself is automatically immutable. The instance may still allow its member variables to be changed via functions or properties, but the variable itself cannot change its value or be reassigned to another value.
One of the big changes in Kotlin from Java is that in Kotlin everything is an object. If you come from a Java background, then you will already be aware that in Java there are special primitive types which are treated differently from objects. They cannot be used as generic types, do not support method/function calls, and cannot be assigned null. An example is the primitive type boolean.
Java introduced wrapper objects to offer a work around in which primitive types are wrapped in objects, so that java.lang.Boolean wraps a boolean in order to smooth over the distinctions. Kotlin removes this necessity entirely from the language by promoting the primitives to full objects.
Whenever possible, the Kotlin compiler will map basic types back to JVM primitives for performance reasons. However, sometimes the values must be boxed, such as when the type is nullable, or when it is used in generics. Boxing is the conversion from a primitive type to a wrapper type that types place whenever an object is required but a primitive is presented.
val int = 123
You will notice that a long value requires the suffix L and a float, the suffix F. The double is used as the default for floating point numbers, and int for integral numbers. The hexadecimal and binary use the prefixes 0x and 0b respectively.
Kotlin does not support automatic widening of numbers, so conversion must be invoked explicitly. Each number has a function that will convert the value to one of the other number types. For example to convert from an integer to a long we can do the following.
val int = 123
val float = 12.34F
The full set of functions for conversions between types is toByte(), toShort(), toInt(), toLong(), toFloat(), toDouble(), toChar().
The usual bitwise operators – left shift, right shift, unsigned right shift, logical and, logical or and exclusive logical or – are supported by Kotlin. Unlike Java, these are not built in operators but named functions instead but can still be invoked like operators:
val leftShift = 1 shl 2 val rightShift = 1 shr 2 val unsignedRightShift = 1 ushr 2
val and = 1 and 0x00001111 val or = 1 or0x00001111 val xor = 1 xor0x00001111 val inv = 1.inv()
Notice that inverse is not a binary operator, but a unary operator and so is invoked using the dot syntax on a number.