PK - Chapter 2 Flashcards
What are the 2 keywords for
declaring variables ?
val - immutable
var - mutable
Define constant foo = Test
val foo = “Test”
Define variable foo with an explicit type of Number and double value of 12.3
var foo: Number = 12.3
Is referential equality guaranteed
on boxed values ?
No
Even if same value, may have
been boxed in different locations.
What are the built-in number types
and their memory sizes ?
There are 6:
Long - 64
Int - 32
Short - 16
Byte - 8
Double - 64
Float - 32
# Define variable foo of type Long with value = 12,333
var foo = 12_333L
# Define variable foo of type double with value 12.33
var foo = 12.33
# Define variable foo with type of Float and value of 12.33
var foo = 12.33F
Create a number literal for each
built-in Number type
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
What is the default type for
loating point numbers ?
Double
What is the default type
for integral numbers ?
Int
Convert an Int to a Long
val fooInt = 1234
val fooLong = fooInt.toLong()
Convert a Float to a Double.
val fooFloat = 12.34F
val fooDouble = fooFloat.toDouble()
What are the boolean operations ?
There are 3:
- negation !
- conjunction &&
- disjunction ||
Bonus:
conjunction and disjunction are lazy
What are the bitwise operators ?
There are 6:
shl - Shift Left
shr - Shift Right
ushr - Unsigned Shift Right
and
or
xor
What are the
Char escape sequences ?
There are 9:
\t
\b
\n
\r
‘
“
$
\u1234
Bonus:
Char type not treated as a number, as in Java.
What is a raw string ?
What is the syntax ?
Typical use ?
- 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
What functions are provided
by an array ?
There are 4:
iterator()
size()
get(index)
set(inces, value)
Bonus:
get() and set() are also available through
bracket syntax.
val element1 = fooArray[0]
What are the primitive array classes ? Why use them ?
There are 8 primitive array classes:
CharArray
BooleanArray
LongArray
IntArray
ShortArray
ByteArray
DoubleArray
FloatArray
Avoids boxing to improve performance.
What are the max values
for built-in Number types ?
They can be retrieved using Type.MAX_VALUE.
Int.MAX_VALUE =
Long.MAX_VALUE =
Short.MAX_VALUE =
Float.MAX_VALUE =
Double.MAX_VALUE =
Create an Int array of 1, 2, 3.
val fooIntArray = arrayOf(1, 2, 3)
How are Kotlin arrays
different from Java arrays ?
Arrays are not part of the language.
Arrays are regular collection classes.
What is the syntax for comments ?
Same as Java.
// line comment
/*
A block comment,
which can span many
lines.
*/
How are packages handled in Kotlin ?
Same as Java.
package com.company.theapp class Foo
How are imports handled in Kotlin ?
Same as Java.
import com.company.theapp.Foo
import com.company.theapp.packagez.*
Give an example of import renaming.
import com.company.theapp.Foo
import com.company/theotherapp.Foo as Foo2
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.
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.
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
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
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)
Give an example of a while loop.
while (true) {
println(“This will print forever!”)
}
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()
What must iterator() return ?
An object that implements:
hasNext() : Boolean
next() : T
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.
How would you iterate over
the characters in a String ?
val foo = “some characters”
for (char in foo) {
println(char)
}
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.
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
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.
Instantiate class Foo.
Constructor takes a single Long argument.
val foo = Foo(100L)
Unlike Java, there is no “new” operator.
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)
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”
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”
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.
What are the visibility modifiers ?
4 visibility modifiers:
- public
- private
- protected
- internal
Note: public is the default visibility
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.
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
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.
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.
Use an if block as an expression.
return if (x==0) methodOne() else methodTwo()
Note: The if clause must have an else
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.
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.
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?
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
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.
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
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
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.
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.
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.
What is the default visibility modifier ?
public
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.
Create a when statement that uses
multiple constants in the condition.
when (x) {
0, 1 -> true
else -> false
}
Create a when statement that
uses a range in the condition.
when (s) {
in 10..49 -> true
else -> false
}
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()
Create a when statement that
uses a smart cast in the condition.
which (anyFoo) {
is String -> anyFoo.startsWith(“Foo”)
else -> false
}
Give an example of
an implicit label.
list.forEach { if (it \< 50) return@forEach else println(it) }
Give an example of
an explicit label.
list.forEach next@ { if (it \< 50) return@next else println(it) }
Describe the Any type.
Any is the uppermost type; analogous to Java’s Object type.
The more commonly used methods include:
- toString
- hashCode
- equals
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.
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.
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 ?)
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() }
How can you make
number literals more readable ?
1_000_000L
1_254.00F
22_158.78
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.
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
What is a function receiver ?
- the instance that corresponds to the
- this* keyword inside the function body
- also referred to as the current receiver