• No results found

Basic types

In document Programming Kotlin (Page 48-52)

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.

Two different values that are boxed might not use the same instance, so referential equality is not guaranteed on boxed values.

Numbers

The built-in number types are as follows:

Type Width Long 64

Int 32

Short 16 Byte 8 Double 64 Float 32

To create a number literal, use one of the following forms:

val int = 123 val long = 123456L val double = 12.34 val float = 12.34F val hexadecimal = 0xAB val binary = 0b01010101

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 long = int.toLong()

Similarly, to convert a float to a double, we use the toDouble function.

val float = 12.34F

val double = float.toDouble()

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.

Booleans

Booleans are rather standard, and support the usual negation, conjunction, and disjunction operations. Conjunction and disjunction are lazily evaluated, so if the left-hand side satisfies the clause, then the right-hand side will not be evaluated:

val x = 1 val y = 2 val z = 2

val isTrue = x < y && x < z val alsoTrue = x == y || y == z

Chars

Chars represent a single character. Character literals use single quotes such as A or Z. Chars also support escaping for the following characters: \t, \b, \n, \r, ', ", \\, and \$.

All unicode characters can be represented using the unicode number, for example, \u1234.

Note that the char type is not treated as a number, as used in Java.

Strings

Just as in Java, strings are immutable. String literals can be created using double quotes or triple quotes. Double quotes create an escaped string. In an escaped string, special

characters, such as new line, must be escaped:

val string = "string with \n new line"

Triple quotes create a raw string. In a raw string, no escaping is necessary, and all characters can be included:

val rawString = """

raw string is super useful for strings that span many lines """

Strings also provide an iterator function which can be used in a for loop. This will be described later in the For loop section.

Arrays

In Kotlin, we can create an array by using the library function arrayOf():

val array = arrayOf(1, 2, 3)

Alternatively, we can create an Array from an initial size and a function, which is used to generate each element:

val perfectSquares = Array(10, { k -> k * k })

Unlike Java, arrays are not treated as special by the language, and are regular collection classes. Instances of arrays provide an iterator function and a size function, as well as a get and a set function. The get and set functions are also available through bracket syntax like many C-style languages:

val element1 = array[0]

val element2 = array[1]

array[2] = 5

To avoid boxing types that will ultimately be represented as primitives in the JVM, Kotlin provides alternative array classes that are specialized for each of the primitive types. This allows performance-critical code to use arrays as efficiently as they would do in plain Java.

The provided classes are ByteArray, CharArray, ShortArray, IntArray, LongArray, BooleanArray, FloatArray, and DoubleArray.

Comments

Comments in Kotlin will come as no surprise to most programmers as they are the same as Java, Javascript, and C, among other languages. Block comments and line comments are supported:

// line comment /*

A block comment can span many lines

*/

Packages

Packages allow us to split code into namespaces. Any file may begin with a package declaration:

package com.packt.myproject class Foo

fun bar(): String = "bar"

The package name is used to give us the fully qualified name (FQN) for a class, object, interface, or function. In the preceding example, the class Foo has the fully qualified name com.packt.myproject.Foo and the top level function bar has the fully qualified name of com.packt.myproject.bar.

Imports

To enable classes, objects, interfaces, and functions to be used outside of the declared package we must import the required class, object, interface, or function:

import com.packt.myproject.Foo

In document Programming Kotlin (Page 48-52)