Kotlin

¡Supera tus tareas y exámenes ahora con Quizwiz!

Omitting the return type is allowed only for functions with an expression body. For functions with a block body that return a value, you have to specify the return type and write the return statements explicitly.

Can we omit return type in expression body functions?

The when construct in Kotlin is more powerful than Java's switch. Unlike switch, which requires you to use constants (enum constants, strings, or number literals) as branch conditions, when allows any objects. fun mix(c1: Color, c2: Color) = when(setOf(c1, c2)) { setOf(RED, YELLOW) -> ORANGE setOf(YELLOW, BLUE) -> GREEN else -> throw Exception("Dirty color") } The when expression matches its argument against all branches in order until some branch condition is satisfied. Thus setOf(c1, c2) is checked for equality: first with setOf(RED, YELLOW) and then with other sets of colors, one after another. If none of the other branch conditions is satisfied, the else branch is evaluated.

Can we use any object in when construct?

No

Can you override an extension function?

Even though the var keyword allows a variable to change its value, its type is fixed. For example, this code doesn't compile: var answer = 42 answer = "no answer" <-- error

Does var keyword allow to change a variable's type?

When you define an extension function, it doesn't automatically become available across your entire project. Instead, it needs to be imported, just like any other class or function. import strings.lastChar val c = "Kotlin".lastChar()

How to access extension function?

joinToString(collection, separator = " ", prefix = " ", postfix = ".")

How to call a function with named params?

Let's say extension function is defined in StringUtil.kt file: /* Java */ char c = StringUtilKt.lastChar("Java");

How to call extension function from Java?

import strings.lastChar as last val c = "Kotlin".last()

How to change a name of an extension function you are importing?

@file: JvmName("StringFunctions") package strings fun joinToString(...): String {...} /* Java */ StringFunctions.joinToString(...);

How to change the file class name?

fun recongnize(c: Char) = when(c) { in '0'..'9' -> println("digit") in 'a'..'z' -> println("character") } println("Kotlin" in setOf("Java", "Scala"))

How to check whether an element is in the range or in the set?

class Person(val name: String)

How to create a class Person with a constructor that takes name as a parameter?

const val UNIX_LINE_SEPARATOR = "\n"

How to create a top level property that corresponds to public static final field in Java?

enum class Color { RED, GREEN, BLUE }

How to create an enum in Kotlin?

enum class Color(val r: Int, val g: Int, val b: Int) { RED(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255); <- semicolon is required fun rgb() = (r * 256 + g) * 256 + b }

How to create an enum with properties and methods?

val list = arrayListOf(1, 2, 3)

How to create arraylist in Kotlin?

val map = hashMapOf(1 to "one", 2 to "two", 3 to "three")

How to create hashmap in Kotlin?

val set = hashSetOf(1, 2, 3)

How to create hashset in Kotlin?

fun <T> joinToString( collection: Collection<T>, separator: String = ", ", prefix: String = " ", postfix: String = " " ): String

How to declare a default param in a function?

The fun keyword is used to declare a function.

How to declare a function in Kotlin?

The function declaration starts with the fun keyword, followed by the function name: max, in this case. It's followed by the parameter list in parentheses. The return type comes after the parameter list, separated from it by a colon. fun max(a: Int, b: Int): Int { return if (a > b) a else b }

How to declare a function?

var StringBuilder.lastChar: Char get() = get(length - 1) set(value: Char) { this.charCharAt(length - 1, value) }

How to declare a mutable extension property?

In Kotlin, properties are a first-class language feature, which entirely replaces fields and accessor methods. You declare a property in a class the same way you declare a variable: with val and var keywords. A property declared as val is read-only, whereas a var property is mutable and can be changed. class Person( val name: String, var isMarried: Boolean ) Basically, when you declare a property, you declare the corresponding accessors (a getter for a read-only property, and both a getter and a setter for a writable one). By default, the implementation of accessors is trivial: a field is created to store the value, and the getter and setter return and update its value. val person = Person("Bob", true) <-- Call the constructor without the "new" keyword println(person.name) println(person.isMarried) <-- You access the property directly, but the getter is invoked

How to declare a property and accessor methods in Kotlin?

There are two keywords to declare a variable: - val (from value)—Immutable reference. A variable declared with val can't be reassigned after it's initialized. It corresponds to a final variable in Java. - var (from variable)—Mutable reference. The value of such a variable can be changed. This declaration corresponds to a regular (non-final) Java variable.

How to declare a variable?

val String.lastChar: Char get() = get(length - 1)

How to declare an immutable extension property?

The parameter type is written after its name.

How to declare parameter type?

val list = arrayListOf("10", "11", "12") for((index, element) in list.withIndex()) { println("$index: $element") }

How to iterate an array list while keeping track of the index of current element?

val binaryReps = TreeMap<Character, String>() for(c in 'A' .. 'Z') { val binary = Integer.toBinaryString(c.toInt()) binaryReps[c] = binary } // iterate map for((letter, binary) in binaryReps) { println("$letter = $binary") }

How to iterate maps in Kotlin?

if(percentage !in 0..100) { throw IllegalArgumentException("Percentage must be between 0 and 100") }

How to throw and exception in Kotlin?

fun getWarmth(color: Color) = when(color) { Color.RED -> "warm" Color.GREEN -> "neutral" Color.BLUE -> "cold" }

How to use a when expression?

In Kotlin there's no regular Java for loop, where you initialize a variable, update its value on every step through the loop, and exit the loop when the value reaches a certain bound. To replace the most common use cases of such loops, Kotlin uses the concepts of ranges. val oneToTen = 1..10 A range is essentially just an interval between two values, usually numbers: a start and an end. You write it using the .. operator. Note that ranges in Kotlin are closed or inclusive, meaning the second value is always a part of the range.

How to use for loop in Kotlin?

fun hello(arg: Array<String>) { println("Hello ${arg[0]}") }

How to use more complex expression in a string template?

Unlike in Java, in Kotlin the throw construct is an expression and can be used as a part of other expressions: val percentage = if(number in 0..100) number else throw IllegalArgumentException()

How to use throw construct as an expression?

fun readNumber(reader: BufferedReader) { val number = try { Integer.parseInt(reader.readLine()) } catche(e: NumberFormatException) { return // or null } println(number) }

How to use try as an expression?

fun readNumber(reader: BufferedReader: Int? { try { val line = reader.readLine() return Integer.parseInt(line) } catch(e: NumberFormatException) { return null } finally { reader.close() } }

How to use try, catch, finally in Kotlin?

Create a file called join.kt with the following contents. package strings fun joinToString(...): String {...} Java code for the above code is generated as follows: package strings; public class JoinKt { public static String joinToString(...) {...} } You can see that the name of the class generated by the Kotlin compiler corresponds to the name of the file containing the function. All top-level functions in the file are compiled to static methods of that class. Therefore, calling this function from Java is as easy as calling any other static method: JoinKt.joinToString(...);

How top level Kotlin functions are compiled to Java class files?

The function can be declared at the top level of a file; you don't need to put it in a class.

Should functions be a part of a class?

Kotlin has while and do-while loops, and their syntax doesn't differ from the corresponding loops in Java: while(condition) { ... } do { ... } while(condition)

What are loop constructs that are similar with Java ones?

val name = "Bob" println("Hello $name") This example introduces a feature called string templates. Like many scripting languages, Kotlin allows "you to refer to local variables in string literals by putting the $ character in front of the variable name. This is equivalent to Java's string concatenation ("Hello, " + name + "!") but is more compact and just as efficient. The compiled code creates a StringBuilder and appends the constant parts and variable values to it.

What is a string template and how to use them?

If a function is written with its body in curly braces, we say that this function has a block body. If it returns an expression directly, it has an expression body. fun max(a: Int, b: Int): Int = if (a > b) a else b

What is an expression body functions?

Conceptually, an extension function is a simple thing: it's a function that can be called as a member of a class but is defined outside of it. To demonstrate that, let's add a method for computing the last character of a string: package strings fun String.lastChar(): Char = this.get(this.length - 1) All you need to do is put the name of the class or interface that you're extending before the name of the function you're adding. This class name is called the receiver type; the value on which you're calling the extension function is called the receiver object.

What is an extension function?

The difference between a statement and an expression is that an expression has a value, which can be used as part of another expression, whereas a statement is always a top-level element in its enclosing block and doesn't have its own value. In Java, all control structures are statements. In Kotlin, most control structures, except for the loops (for, do, and do/while) are expressions. The ability to combine control structures with other expressions lets you express many common patterns concisely, as you'll see later in the book.

What is the difference between a statement and an expression?

In the body of an extension function, you use this as you'd use it in a method. And, as in a regular method, you can omit it: fun String.lastChar(): Char = get(length - 1) In the extension function, you can directly access the methods and properties of the class you're extending, as in methods defined in the class itself. Note that extension functions don't allow you to break encapsulation. Unlike methods defined in the class, extension functions don't have access to private or protected members of the class.

What is the difference between extension function and regular function?

In when the code finds the branch corresponding to the passed color value. Unlike in Java, you don't need to write break statements in each branch (a missing break is often a cause for bugs in Java code). If a match is successful, only the corresponding branch is executed. You can also combine multiple values in the same branch if you separate them with commas. fun getWarmth(color: Color) = when(color) { Color.RED, Color.ORANGE, Color.YELLOW -> "warm" Color.GREEN -> "neutral" Color.BLUE -> "cold" }

What is the difference of when in Kotlin and switch in Java?

By default, you should strive to declare all variables in Kotlin with the val keyword. Change it to var only if necessary.

What keyword should you strive to use to all variables?

In Java, you start a variable declaration with a type. This wouldn't work for Kotlin, because it lets you omit the types from many variable declarations. Thus in Kotlin you start with a keyword, and you may (or may not) put the type after the variable name. If a variable doesn't have an initializer, you need to specify its type explicitly: val answer: Int answer = 42

Why a variable type comes after its name in Kotlin?

fun fizzBuzz(i: Int) = when { i % 15 == 0 -> "FizzBuzz" i % 3 == 0 -> "Fizz" i % 5 == 0 -> "Buzz" else -> "$i " } for(i in 1..100) { println(fizzBuzz(i)) }

Write a code for FizzBuzz game in Kotlin


Conjuntos de estudio relacionados

BIO110 Unit 5 Study Guide Climate Change

View Set

Art Appreciation Exam 3 CH 8,9,10

View Set

CITI: Investigator Obligations in FDA-Regulated Research

View Set

SWIMMING The Four (4) Competition Strokes:

View Set

ABO and H blood group system study questions

View Set

Ch 24: International and Space Law

View Set

General insurance exam questions

View Set