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
Q

How are imports handled in Kotlin ?

A

Same as Java.

import com.company.theapp.Foo
import com.company.theapp.packagez.*

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

Give an example of import renaming.

A

import com.company.theapp.Foo
import com.company/theotherapp.Foo as Foo2

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

Give an example of string templates.

A

val name = “Sam”
val nameHello = “Hello $name”
val nameLength = “$nameHello. Your name has ${name.length} characters.”

Bonus:

Also called string interpolation.

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

Give an example of string interpolation.

A

val name = “Sam”
val nameHello = “Hello $name”
val nameLength = “$nameHello. Your name has ${name.length} characters.”

Bonus:

Also called string templates.

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

Explain ranges.

A

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

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

Explain the “in” operator.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q
Give an example of using step()
and reversed() with a range.
A

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
Q

Give an example of a while loop.

A

while (true) {
println(“This will print forever!”)
}

33
Q

Give an example of a for loop.

A

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
Q

What must iterator() return ?

A

An object that implements:

hasNext() : Boolean
next() : T

35
Q

Why would you use a Range
instead of a List ?

A

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
Q

How would you iterate over
the characters in a String ?

A

val foo = “some characters”
for (char in foo) {
println(char)
}

37
Q

What is the key difference between
Java and Kotlin for exception handling ?

A
  • 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
Q

Explain the rules for
coding Kotlin exceptions.

A

​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
Q

Give an example of
a try-catch block.

A

try {
something()
} catch (e: SomeException) {
println(“caught SomeException”)
} finally {
cleanup()
}

Bonus:

At least one catch or finally block
is required.

40
Q

Instantiate class Foo.

Constructor takes a single Long argument.

A

val foo = Foo(100L)

Unlike Java, there is no “new” operator.

41
Q

Describe referential equality
versus structural equality.

A

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
Q

Explain the usage of “this”.

A
  • “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
Q

What is the current receiver ?

A
  • 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
Q

How would you refer to member
variable “address” of an instance
of type Building in the object graph ?

A
inner class Foo() {
 fun printAddress() = println(this@Building.address)
}

Note the use of the “@” notation.

45
Q

What are the visibility modifiers ?

A

4 visibility modifiers:

  • public
  • private
  • protected
  • internal

Note: public is the default visibility

46
Q

Explain the private visibility modifier.

A
  • 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
Q

Explain the protected visibility modifier.

A
  • 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
Q

Explain the internal modifier.

A

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
Q

Explain expression versus statement.

A
  • 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
Q

Use an if block as an expression.

A

return if (x==0) methodOne() else methodTwo()

Note: The if clause must have an else

51
Q

Use a try block as an expression.

A

val success = try {
doSomething()
true
} catch (e: IOException) {
false
}

Note that the last line of each
block returns a boolean.

52
Q

Use a code block as an expression.

A

val success = {
doSomething()
doSomethingMore() // returns a boolean
}

Note: The last line of the code block returns
a boolean.

53
Q

Explain null syntax.

A
  • 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
Q

Explain the “is” operator.

A
  • 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
Q

Explain smart casts.

A

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
Q

Explain explicit casting.

A
* 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
Q

What is the “safe cast” operator ?

A

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
Q

Explain the when expression.

A

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
Q

Create a when statement
with an argument.

A

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
Q

Explain the different ways to construct
the conditions of a when statement
​which has an argument ?

A
  • 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
Q

What is the default visibility modifier ?

A

public

62
Q

Explain the different ways to construct
the conditions of a when statement
which does not have an argument ?

A
  • 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
Q

Create a when statement that uses
multiple constants in the condition.

A

when (x) {
0, 1 -> true
else -> false
}

64
Q

Create a when statement that
uses a range in the condition.

A

when (s) {
in 10..49 -> true
else -> false
}

65
Q

Create a when statement that
uses a collection in the condition.

A

which (x) {
in someCollectionOfX -> true
else -> false
}

Note: you can specify that the argument
is in any object that implements iterator()

66
Q

Create a when statement that
uses a smart cast in the condition.

A

which (anyFoo) {
is String -> anyFoo.startsWith(“Foo”)
else -> false
}

67
Q

Give an example of
an implicit label.

A
list.forEach {
 if (it \< 50) return@forEach
 else println(it)
}
68
Q

Give an example of
an explicit label.

A
list.forEach next@ {
 if (it \< 50) return@next
 else println(it)
}
69
Q

Describe the Any type.

A

Any is the uppermost type; analogous to Java’s Object type.

The more commonly used methods include:

  • toString
  • hashCode
  • equals
70
Q

Describe the Unit type.

A
  • 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
Q

Describe the Nothing type.

A
  • 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
Q

Explain the
return-at-label syntax.

A
  • 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
Q

Explain a lambda.

A
  • 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
Q

How can you make
number literals more readable ?

A

1_000_000L

1_254.00F

22_158.78

75
Q

Write a lambda with multiple
arguments, that does not
use them all.

A

someMethod(firstArg) { _, secondArg ->
someOtherMethod(secondArg) }

map.forEach { (_, value) -> println($value!!!”) }

Note the destructuring of the pair in the
second example.

76
Q

Summarize:

  • Any
  • Unit
  • Nothing
A
  • 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
Q

What is a function receiver ?

A
  • the instance that corresponds to the
  • this* keyword inside the function body
  • also referred to as the current receiver