# *_Define a function_* "foo" with an Int parameter and an Int return of the parameter squared.
fun foo(pInt: Int) = pInt * pInt
# Define a function "foo" with a String parameter and a String return of the parameter contatenated with "Hello World".
fun foo(pString: String) = “${pString} and Hello World”
What is a single expression function ?
Describe member functions.
What is the DRY principle ?
Don’t Repeat Yourself
Describe Local Functions.
Use local functions inside a for loop
and when clause.
fun fizzBuzz(start: Int, end: Int) {
for (k in start..end) {
fun isFizz() = k % 3 == 0
fun isBuzz() = k % 5 == 0
when (
isFizz() && isBuzz() -\> println("Fizz Buzz")
isFizz() -\> println("Fizz")
isBuzz() -\> println("Buzz")
}
}
}Explain top-level functions.
What are the 4 types of functions ?
Explain named parameters.
Explain default parameters.
Explain extension functions.
Why create an extension function ?
* frequently used to add a function to a final class, or a class in an SDK that you do not want to extend * avoids creating subclasses, or wrappers, which would require code changes to use the new class
# Define extension function "bar{}"
for class "Foo".fun Foo.bar() = “Foo Bar !”
Explain extension function precedence.
Extension function are resolved in the following order:
Create an extension function that handles nulls.
fun Any?.safeEquals(other: Any?): Boolean {
if (this == null && other == null) return true
if (this == null return false
return this.equals(other)
}
What is a member extension function ?
Extension functions are usually declared at the top level.
A member extension function is defined inside a class.
Its scope is limited and no import is required.
Give an example of a mapping receiver
versus an extension receiver.
Extension receiver is an object of the class on which the extension was defined and called.
A method in a class is called the dispatch receiver.
When there is shadowing of names, the extension receiver
will take precedence, so you must qualify the dispatch receiver.
private fun String.stringAdd() {
map.put(this@ContainerClass.hashCode(), this)
}
Create a companion object extension.
fun Int.Companion.random() : Int {
val random = Random()
return random.nextInt()
}
val int = Int.random()
Explain the types; Pair and Triple.
These contain 2 and 3 identical types, respectively.
An example of Pair…
fun getPair() = Pair(getSomeInt(), getAnotherInt())
val (firstInt, secondInt) = getPair()
val myPair = “London” to “Paris”
Explain an infix function .
infix fun concat(other: String) = this + other
val myConcat = “Hello “ concat “World!”
Explain operator overloading .
What is the list of basic operators
that can be overloaded ?
plus
minus
times
div
mod
rangeTo
unaryPlus
unaryMinus
not
What is the list of advanced operators
that can be overloaded ?
contains ( in )
get / set ( [] )
invoke (makes a class look like a function)
compareTo ( <, >, <=, >= )