PK - Chapter 2 Flashcards

1
Q

What are the 2 keywords for
declaring variables ?

A

val - immutable

var - mutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Define constant foo = Test

A

val foo = “Test”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Define variable foo with an explicit type of Number and double value of 12.3

A

var foo: Number = 12.3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is referential equality guaranteed
on boxed values ?

A

No

Even if same value, may have
been boxed in different locations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the built-in number types
and their memory sizes ?

A

There are 6:

Long - 64

Int - 32

Short - 16

Byte - 8

Double - 64

Float - 32

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
# Define variable foo of type
Long with value = 12,333
A

var foo = 12_333L

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
# Define variable foo of type
double with value 12.33
A

var foo = 12.33

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
# Define variable foo with type
of Float and value of 12.33
A

var foo = 12.33F

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Create a number literal for each
built-in Number type

A

There are 6 build-in Number types:

Long
val foo = 1234L
Int
val foo = 1234
Double
val foo = 12.34
Float
val foo = 12.34F
Hexadecimal
val foo = 0xAB
Binary
val foo = 0b01010101

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the default type for
loating point numbers ?

A

Double

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the default type
for integral numbers ?

A

Int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Convert an Int to a Long

A

val fooInt = 1234

val fooLong = fooInt.toLong()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Convert a Float to a Double.

A

val fooFloat = 12.34F

val fooDouble = fooFloat.toDouble()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the boolean operations ?

A

There are 3:

  • negation !
  • conjunction &&
  • disjunction ||

Bonus:
conjunction and disjunction are lazy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the bitwise operators ?

A

There are 6:

shl - Shift Left
shr - Shift Right
ushr - Unsigned Shift Right
and
or
xor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are the
Char escape sequences ?

A

There are 9:

\t
\b
\n
\r



$
\u1234

Bonus:
Char type not treated as a number, as in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a raw string ?
What is the syntax ?
Typical use ?

A
  • No escaping is necessary, so all characters can be included
  • The string starts and ends with 3 double quotes (“””)
    val foo = “””

This is the first line
second line of the string
third line with special character / in the string”””

  • Typically used for multi-line strings or regex strings
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What functions are provided
by an array ?

A

There are 4:

iterator()
size()
get(index)
set(inces, value)

Bonus:

get() and set() are also available through
bracket syntax.

val element1 = fooArray[0]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the primitive array classes ? Why use them ?

A

There are 8 primitive array classes:

CharArray
BooleanArray
LongArray
IntArray
ShortArray
ByteArray
DoubleArray
FloatArray

Avoids boxing to improve performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the max values
for built-in Number types ?

A

They can be retrieved using Type.MAX_VALUE.

Int.MAX_VALUE =
Long.MAX_VALUE =
Short.MAX_VALUE =
Float.MAX_VALUE =
Double.MAX_VALUE =

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Create an Int array of 1, 2, 3.

A

val fooIntArray = arrayOf(1, 2, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How are Kotlin arrays
different from Java arrays ?

A

Arrays are not part of the language.

Arrays are regular collection classes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the syntax for comments ?

A

Same as Java.

// line comment

/*
A block comment,
which can span many
lines.
*/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How are packages handled in Kotlin ?

A

Same as Java.

package com.company.theapp
class Foo
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How are imports handled in Kotlin ?
Same as Java. import com.company.theapp.Foo import com.company.theapp.packagez.\*
26
Give an example of *_import renaming._*
import com.company.theapp.Foo import com.company/theotherapp.Foo as Foo2
27
Give an example of *_string templates_*.
val name = "Sam" val nameHello = "Hello $name" val nameLength = "$nameHello. Your name has ${name.length} characters." Bonus: Also called string interpolation.
28
Give an example of *_string interpolation_*.
val name = "Sam" val nameHello = "Hello $name" val nameLength = "$nameHello. Your name has ${name.length} characters." Bonus: Also called string templates.
29
Explain *ranges*.
A range is an interval that has a start value and an end value. Any types which are comparable can be used to create a range, using the ".." operator val aToZ = "a".."z" val oneToNine = 1..9
30
Explain the *_"in" operator_*.
The "in" operator is used to test whether a given value is included in the range. val aToZ = "a".."z" val isTrue = "c" in aToZ
31
``` Give an example of using step() and reversed() with a range. ```
val oddNumbers = (1..50).step(2) val countingDownEvenNumbers = (2..100).step(2).reversed() Bonus: val countDown = 100.downTo(0) val foo = 10 val rangeTo = foo.rangeTo(20)
32
Give an example of a *_while loop_*.
while (true) { println("This will print forever!") }
33
Give an example of a *_for loop_*.
val fooList = listOf(1,2,3,4) for (k in fooList) { println(k) } Note the required use of the "in" keyword. Bonus: "for" loop can be used with any object that implements iterator()
34
What must iterator() return ?
An object that implements: hasNext() : Boolean next() : T
35
Why would you use a Range instead of a List ?
Ranges are compiled into an index-based collection for loops that are supported directly on the JVM, so the iterator introduces no performance penalty.
36
How would you iterate over the characters in a String ?
val foo = "some characters" for (char in foo) { println(char) }
37
What is the key difference between Java and Kotlin for exception handling ?
* All exceptions in Kotlin are unchecked. * In Java, unchecked exceptions are those that do not need to be added to method signatures. * In Kotlin, exceptions are never part of the method signature.
38
Explain the rules for coding *_Kotlin exceptions_*.
​There are 4 rules: * 1 try block * zero or more catch blocks * zero or one finally block * at least one catch or finally block
39
Give an example of a *_try-catch block_*.
try { something() } catch (e: SomeException) { println("caught SomeException") } finally { cleanup() } Bonus: At least one catch or finally block is required.
40
*_Instantiate class_* Foo. Constructor takes a single Long argument.
val foo = Foo(100L) Unlike Java, there is no "new" operator.
41
Describe *_referential equality_* versus *_structural equality_*.
Referential equality 2 objects point to the same memory address Operators: === !== Structural equality determined by using the equals function of the class Operators (null safe): == (not the same as Java) != (not the same as Java)
42
Explain the usage of "this".
* "this" refers to the current receiver * Current receiver is the instance that received the invocation of the function, or in the case of *also* and *let*, the current receiver is the containing object of the object on which they are called * Extension functions can reference "this"
43
What is the *_current receiver_* ?
* Current receiver is the instance that received the invocation of a function, or in the case of *also* and *let*, the current receiver is the containing object of the object on which they are called * Can be referenced inside the function with "this" * Has access to members of "this"
44
How would you refer to member variable "address" of an instance of type Building in the object graph ?
``` inner class Foo() { fun printAddress() = println(this@Building.address) } ``` Note the use of the "@" notation.
45
What are the *_visibility modifiers_* ?
4 visibility modifiers: * public * private * protected * internal Note: public is the default visibility
46
Explain the *_private_* visibility modifier.
* Private top-level functions, classes or interfaces can only be accessed from the same file. * Inside a class, interface, or object, any private function or property is only visible to other members. Bonus: Public is the default visibility.
47
Explain the *_protected_* visibility modifier.
* Top-level functions, classes or interfaces **cannot** be protected * Only functions or properties inside a class or interface can be protected. They are only visible to: * members of that class or interface * subclasses or subinterfaces * classes that implement the interface
48
Explain the *_internal_* modifier.
Any code that is marked internal is visible from other classes and functions inside the same module. This can be a Maven or Gradle module, or an IntelliJ/Android module.
49
Explain expression versus statement.
* An expression evaluates to a value. "hello".startsWith("h") * A statement has no resulting value returned. val a = 1 Bonus: In Kotlin, if...else and try...catch blocks are expressions. Expressions can also be code blocks. The last line of the block must be an expression.
50
Use an *_if block_* as an expression.
return if (x==0) methodOne() else methodTwo() Note: The if clause must have an else
51
Use a *_try block_* as an expression.
val success = try { doSomething() true } catch (e: IOException) { false } Note that the last line of each block returns a boolean.
52
Use a *_code block_* as an expression.
val success = { doSomething() doSomethingMore() // returns a boolean } Note: The last line of the code block returns a boolean.
53
Explain *_null syntax_*.
* A variable which can be assigned null must be declared with a "?". var fooString: String? = null Bonus: Extension functions defined for String are not available for type String?
54
Explain the *_"is" operator_*.
* Equivalent to Java's *instanceof* * Used for type checking at run time when(x) { is String -\> println(x.toUpper()) else -\> Unit } * "!is" can also be used
55
Explain *_smart casts_*.
If a variable has been type checked (is), it is *implicitly cast* to the *more specific type* within the *remainder* of that scope/block.
56
Explain *_explicit casting_*.
``` * Use the "as" keyword to cast an object fun length(fooAny: Any): Int { ``` val aString = fooAny as String return aString.length } * Use the "as?" Bonus: ``` val fooString: String? = fooAny as String // in case fooAny is null or cannot be cast to a String ```
57
What is the *_"safe cast"_* operator ?
If you want to avoid the ClassCastException when a cast fails, use the "as?" operator. This will return null if the cast fails. val fooAny = "some string" val someString: String? = fooAny as? String val aFile: File? = fooAny as? File // aFile will equal null
58
Explain the *_when_* expression.
There are 2 forms of *_when_* statement: * with an argument a replacement for the Java *_switch_* statement * without an argument a replacement for the Java *_if..else_* construct The else clause is required, unless the compiler can infer that all possible conditions have been satisfied.
59
Create a *_when statement_* with an argument.
when (x) { 0 -\> println("x is 0") 1 -\> println("x is 1") else -\> println("x is neither 0 or 1") } when (x) { 0, 1 -\> println("x is 0 or 1") else -\> println("x is neither 0 or 1") } Note the required use of *_else_*, since the compiler cannot infer that all possible conditions have been satisfied.
60
Explain the different ways to construct the *_conditions of a when statement_* ​which has an argument ?
* the condition must be the same type as the argument * condition can be a constant * constants can be combined into a single condition, ​seperated by commas * can use any function or expression that resolves to ​the same type as the argument * ranges (of the same type) also supported, using ​the *_in_* operator * collections (of the same type) also supported, ​using the *_in_* operator * smart casts can be used, as in when (any) { is String -\> any.startsWith("Foo") else -\> false ​} * there must always be an *else* condition, unless the compiler can infer that all possible conditions have been satisfied. * There is no restriction on combining these different types of conditions.
61
What is the *_default visibility modifier_* ?
public
62
Explain the different ways to construct the *_conditions of a when statement_* which does not have an argument ?
* each condition must resolve to a boolean * the else clause is required, unless the compiler can infer that all possible conditions (true / false) have been satisfied.
63
Create a *_when statement_* that uses *_multiple constants in the condition_*.
when (x) { 0, 1 -\> true else -\> false }
64
Create a *_when statement_* that uses *_a range in the condition_*.
when (s) { in 10..49 -\> true else -\> false }
65
Create a *_when statement_* that uses *_a collection in the condition_*.
which (x) { in someCollectionOfX -\> true else -\> false } Note: you can specify that the argument is in any object that implements *iterator()*
66
Create a *_when statement_* that uses a *_smart cast in the condition_*.
which (anyFoo) { is String -\> anyFoo.startsWith("Foo") else -\> false }
67
Give an example of an *_implicit label_*.
``` list.forEach { if (it \< 50) return@forEach else println(it) } ```
68
Give an example of an *_explicit label_*.
``` list.forEach next@ { if (it \< 50) return@next else println(it) } ```
69
Describe the *_Any type_*.
*_Any_* is the uppermost type; analogous to Java's Object type. The more commonly used methods include: * toString * hashCode * equals
70
Describe the *_Unit type_*.
* The *_Unit type_* is equivalent to void in Java * Unit is a proper type, with a singleton instance * The singleton instance of Unit is returned when a function specifies a return type of Unit, or does not specify any return type.
71
Describe the *_Nothing type_*.
* Nothing is a type that has no instances * Nothing is a *_bottom type_*, the subtype of all classes * can be used to inform the compiler that a function never completes normally (it might loop forever, or always throw an exception) * an empty list of Nothing could be assigned to a reference expecting a list of Strings. This is used in emptyList(), emptySet() and etc.
72
Explain the *_return-at-label_* syntax.
* return@someLabel * someLabel@ * can label a code block or any statement inside the current scope * can also use an implicit label (the containing iterator ?)
73
Explain a *_lambda_*.
* defined inside brackets * its parameters, if any, are declared before the right arrow * when there are multiple arguments, use the underscore to indicate unused arguments * arrow notation and arguments are optional if not used * if only 1 parameter, arrow and argument can be omitted; referring the the parameter with "it" * if the last parameter to a function is a function, and you are passing a lambda expression, you can specify it outsde the parenthesis * if the method only has one function parameter, the parenthesis may be omitted val result = someMethod(firstParam, { someArg: String -\> someOtherMethod(someArg) } ) val result = someMethod(firstParam) { someOtherMethod() } val result2 = methodSimple { someOtherMethod() }
74
How can you make *_number literals more readable_* ?
1\_000\_000L 1\_254.00F 22\_158.78
75
Write a lambda with multiple arguments, that does not use them all.
someMethod(firstArg) { \_, secondArg -\> someOtherMethod(secondArg) } map.forEach { (\_, value) -\> println($value!!!") } Note the *destructuring* of the pair in the second example.
76
Summarize: * Any * Unit * Nothing
* Any "top type" for all objects equivalent to Java *Object* * Unit a singleton returned by functions without a return type equivalent to Java *null* * Nothing "bottom type" for all objects indicates that a function never returns used to create empty collection
77
What is a *function receiver* ?
* the instance that corresponds to the * this* keyword inside the function body * also referred to as the *current receiver*