Lecture 1: Kotlin Programming
Document Details
Uploaded by ThrilledIridium
Minia University
Tags
Summary
This lecture introduces Kotlin, a programming language that runs on the Java Virtual Machine. It covers basic data types, variables, and operators in Kotlin. The lecture is likely part of a computer science course, focusing on programming concepts.
Full Transcript
Lecture 1 DATA TYPES AND IF STATEMENT Kotlin Kotlin is a new language that targets the Java platform; its programs run on the JVM (Java Virtual Machine), which puts it in the company of languages like Groovy, Scala, Jython, and Clojure, to name a few. Kotlin is from JetBrains, the...
Lecture 1 DATA TYPES AND IF STATEMENT Kotlin Kotlin is a new language that targets the Java platform; its programs run on the JVM (Java Virtual Machine), which puts it in the company of languages like Groovy, Scala, Jython, and Clojure, to name a few. Kotlin is from JetBrains, the creators of IntelliJ, PyCharm, WebStorm, ReSharper, and other great development tools. In 2011, JetBrains unveiled Kotlin; the following year, they open-sourced Kotlin under the Apache 2 license. At Google I/O 2017, Google announced first-class support for Kotlin on the Android platform. If you’re wondering where the name Kotlin came from, it’s the name of an island near St. Petersburg, where most of the Kotlin team members are located. According to Andrey Breslav of JetBrains, Kotlin was named after an island, just like Java was named after the Indonesian island of Java. Kotlin Syntax Kotlin Syntax The fun keyword is used to declare a function. A function is a block of code designed to perform a particular task. In the example above, it declares the main() function. The main() function is something you will see in every Kotlin program. This function is used to execute code. Any code inside the main() function's curly brackets {} will be executed. For example, the println() function is inside the main() function, meaning that this will be executed. The println() function is used to output/print text, and in our example it will output "Hello World". Kotlin Variables Variables are containers for storing data values. To create a variable, use var or val, and assign a value to it with the equal sign (=): Syntax: var variableName = value val variableName = value The difference between var and val is that variables declared with the var keyword can be changed/modified, while val variables cannot. Variables A variable is something that we use to manipulate data or, more precisely, a value. Values are things that you can store, manipulate, print, push, or pull from the network. For us to be able to work with values, we need to put them inside variables. A variable in Kotlin is created by declaring an identifier using the var keyword followed by the type, like in the statement: var foo: Int Now that the variable is declared, we can assign a value to it, like so: foo = 10 and then, use it in a function, like the following: println(foo) We can declare and define variables on the same line, like in Java. Here’s the var foo example again. var foo: Int = 10 println(foo) **** We don’t always have to declare or write the type of the variables; Kotlin is smart enough to figure out the type when you assign a literal value to variable; it’s called type inference. Keywords Keywords are reserved terms that have special meaning to the compiler, and as such, they cannot be used as identifiers for any program elements such as classes, variable names, function names, and interfaces. Kotlin has hard, soft, and modifier keywords. The hard keywords are always interpreted as keywords and cannot really be used as identifiers. Some examples of these are as, break, class, continue, do, else, false, while, this, throw, try, super, and when. Soft keywords act as reserved words in certain context where they are applicable; otherwise, they can be used as a regular identifier. Some examples of soft keywords are the following: file, finally, get, import, receiver, set, constructor, delegate, get, by, and where. Keywords Cont’d Finally, there are modifier keywords. These things act as reserved words in modifier lists of declarations; otherwise, they can be used as identifiers. Some examples of these things are the following: abstract, actual, annotation, companion, enum, final, infix, inline, lateinit, operator, and open. Operators or Symbol Operators or What It Means Symbol +, -, *, /, % These are the usual mathematical operators—they do exactly what you expect them to do. But we need to note that the asterisk or star symbol (*) is also used to pass an array to a vararg parameter. = The equal symbol is used for the assignment statement. +=, -=, *=, /=, These are augmented assignment operators. The += can be used like this a += 1, which is short for a %= = a + 1; the -= can be used like a -= 1, which is short for a = a -1, and so on. &&, ||, ! When you need to construct complex or compound logical operations, you will use these operators. logical 'and', When one of the operands evaluates to false, the other operand will no longer be evaluated and the 'or', 'not' whole expression evaluates to false. While logical 'and' does not perform short-circuit evaluation; operators think of it as the equivalent of the & operator in Java. The short-circuit or (||) acts the same as in Java. Kotlin doesn’t have the single pipe operator; instead, it has the 'or' operator, which performs a logical OR without short-circuiting. , = Comparison operators. Kotlin translates these to calls to compareTo()—no primitive types, remember? Operators or Symbol ==, != These are equality operators. Since Kotlin doesn’t have primitive types, you can use these operators to compare any type, basic or otherwise: fun main(args: Array) { var a = "Hello" var b = "Hello" if (a == b) { // this evaluates to true println("$a is equal to $b") }} ===, !=== Referential equality is checked by the === operation (and its negated counterpart !==). a === b evaluates to true if and only if a and b point to the same object. For example, var p1 = Person("John") var p2 = Person("John") if(p1 === p2) { // false println("p1 == p2") } In the above example, p1 and p2 do not point to the same object; hence, the triple equals will not evaluate to true. Basic Types: Numbers and Literal Constants Every number type can be converted to any of the number types. That means all Double, Float, Int, Long, Byte, and Short types support the following member functions: toByte() : Byte toShort() : Short toInt() : Int toLong() : Long toFloat() : Float toDouble() : Double toChar() : Char Characters Characters in Kotlin cannot be treated directly as numbers. You can’t do things like the following: fun checkForKey(keyCode:Char) { if (keyCode == 97) { // won't work, keyCode is not a number } } Character literals are created by using single quotes, like var enterKey = 'a' Member Functions of the Character Type val a = 'a' println(a.isLowerCase()) // true println(a.isDigit()) // false println(a.toUpperCase()) // A val b: String = a.toString() // converts it to a String Booleans Booleans are represented by the literals true and false. Kotlin doesn’t have the notion of truthy and falsy values, like in other languages such as Python or JavaScript. It means that for constructs that expect a Boolean type, you have to supply either a Boolean literal, variable, or expression that will resolve to either true or false. var count = 0 if (count) println("zero") // won't work if ("") println("empty") // won't work either Arrays Kotlin doesn’t have an array object like the one created in Java using the square braces syntax. The Kotlin array is a generic class—it has a type parameter. We’ve been using Kotlin arrays for quite some time now because the small code snippets and the “Hello World” example in the previous chapter have featured the use of Arrays. The argument to the main function is actually an Array of String. Let’s see that main function again, just as a refresher. fun main(args:Array) { } There are a couple of ways to create an array. They can be created using the arrayOf() and arrayOfNulls() functions, and finally, they can be created using the Array constructor. arrays are used to store multiple values in a single variable, instead of creating separate variables for each arrayOf() value. To create an array, use the arrayOf() function, and place the values in a comma-separated list inside it: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") Access the Elements of an Array You can access an array element by referring to the index number, inside square brackets. In this example, we access the value of the first element in cars: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") println(cars) // Outputs Volvo Array Length / Size To find out how many elements an array have, use the size property: Example: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") println(cars.size) // Outputs 4 Check if an Element Exists : You can use the in operator to check if an element exists in an array: fun main() { val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") if ("Volvo" in cars) { println("It exists!") } else { println("It does not exist.") } } Loop Through an Array Often when you work with arrays, you need to loop through all of the elements. You can loop through the array elements with the for loop, which you will learn even more about in the next chapter. The following example outputs all elements in the cars array: fun main() { val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") for (x in cars) { println(x) } } Working With the Array Type fun main(args: Array) { var emptyArray = arrayOfNulls(2) ➊ emptyArray = "Hello" ➋ emptyArray = "World" for (i in emptyArray.indices) println(emptyArray[i]) ➌ for (i in emptyArray) println(i) ➍ var arrayOfInts = arrayOf(1,2,3,4,5,6) ➎ arrayOfInts.forEach { e -> println(e) } ➏ var arrayWords = "The quick brown fox".split(" ").toTypedArray() ➐ arrayWords.forEach { item -> println(item) } } Strings and String Templates The easiest way to create a String is to use the escaped string literal—escaped strings are actually the kind of strings we know from Java. These strings may contain escape characters like \n, \t, \b, etc. See the code snippet below. var str: String = "Hello World\n“ A raw string is created by using triple quote delimiter. They may not contain escape sequences, but they can contain new lines, like For example, in Java, in order to create properly a String containing a Windows-style file path to a resource located at C:\Repository\read.me, we should define it in this way: String path = "C:\\Repository\\read.me“ In Kotlin, we may use the triple-quoted notation in order to achieve the same result: val path = """C:\Repository\read.me""" A couple more things we need to know about Kotlin strings are as follows: 1. They have iterators, so we can walk through the characters using a for loop: val str = "The quick brown fox" for (i in str) println(i) 2. Its elements can be accessed by the indexing operator (str[elem]), println(str[2)) // returns 'e' 3. We can no longer convert numbers (or anything else for that matter) to a String by simply adding an empty String literal to it: var strNum = 10 + "" // this won't work anymore var strNum = 10.toString() // we have to explicitly convert now still use String.format and System.out.printf in Kotlin Example: Using String.format and printf var name = "John Doe" var email = "[email protected]" var phone = "(01)777-1234" var concat = String.format("name: %s | email: %s | phone: %s", name, email, phone) println(concat) // prints // name: John Doe | email: [email protected] | phone: (01)777-1234 The preferred way to do string composition in Kotlin is by using string templates, like var concat = "name: $name | email: $email | phone: $phone" println(concat) // prints // name: John Doe | email: [email protected] | phone: (01)777-1234 String Length A String in Kotlin is an object, which contain properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable. For example, the length of a string can be found with the length property: var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ“ println("The length of the txt string is: " + txt.length) String Functions There are many string functions available, for example toUpperCase() and toLowerCase(): var txt = "Hello World" println(txt.toUpperCase()) // Outputs "HELLO WORLD" println(txt.toLowerCase()) // Outputs "hello world" Comparing Strings The compareTo(string) function compares two strings and returns 0 if both are equal: var txt1 = "Hello World" var txt2 = "Hello World" println(txt1.compareTo(txt2)) // Outputs 0 (they are equal) Finding a String in a String The indexOf() function returns the index (the position) of the first occurrence of a specified text in a string (including whitespace): var txt = "Please locate where 'locate' occurs!" println(txt.indexOf("locate")) // Outputs 7 String Concatenation The + operator can be used between strings to add them together to make a new string. This is called concatenation: Eaxmple: var firstName = "John" var lastName = "Doe" println(firstName + " " + lastName) You can also use the plus() function to concatenate two strings: Example: var firstName = "John " var lastName = "Doe" println(firstName.plus(lastName)) String Templates/Interpolation Instead of concatenation, you can also use "string templates", hich is an easy way to add variables and expressions inside a string. Just refer to the variable with the $ symbol: Example: var firstName = "John" var lastName = "Doe" println("My name is $firstName $lastName") Kotlin Conditions and If..Else Kotlin has the following conditionals: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use when to specify many alternative blocks of code to be executed Kotlin if Use if to specify a block of code to be executed if a condition is true. Syntax: if (condition) { // block of code to be executed if the condition is true } Example: if (20 > 18) { println("20 is greater than 18") } We can also test variables: Example: fun main() { val x = 20 val y = 18 if (x > y) { println("x is greater than y") } } Kotlin else Use else to specify a block of code to be executed if the condition is false. Syntax: if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } Example: fun main() { val time = 20 if (time < 18) { println("Good day.") } else { println("Good evening.") } } Kotlin else if Use else if to specify a new condition if the first condition is false. Syntax: if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false } Example: val time = 22 if (time < 10) { println("Good morning.") } else if (time < 20) { println("Good day.") } else { println("Good evening.") } // Outputs "Good evening." Kotlin If..Else Expressions In Kotlin, you can also use if..else statements as expressions (assign a value to a variable and return it): Example: val time = 20 val greeting = if (time < 18) { "Good day." } else { "Good evening." } println(greeting) Note: You can ommit the curly braces {} when if has only one statement: ** When using if as an expression, you must also include else (required). Example: fun main() { val time = 20 val greeting = if (time < 18) "Good day." else "Good evening." println(greeting) }