Skip to content

Instantly share code, notes, and snippets.

@sagarpatel288
sagarpatel288 / LocalConstant.kt
Last active June 15, 2020 02:56
An example to show local final in kotlin
/**
* 6/15/2020
* An example to show local final
* @author srdpatel
* @since 1.0
*/
class LocalConstant {
val CONSTANT = "allows all data types"
}
@sagarpatel288
sagarpatel288 / applyDefinition.kt
Created June 5, 2020 03:22
The definition of a scope function: apply
public inline fun <T> T.apply(block: T.() -> Unit): T {
/*...*/
block()
return this
}
@sagarpatel288
sagarpatel288 / alsoDefinition.kt
Created June 5, 2020 03:16
The definition of a scope function: also
public inline fun <T> T.also(block: (T) -> Unit): T {
/*...*/
block(this)
return this
}
@sagarpatel288
sagarpatel288 / runDefinition.kt
Created June 5, 2020 03:06
The definition of a scope function: T.run
public inline fun <T, R> T.run(block: T.() -> R): R {
/*...*/
return block()
}
@sagarpatel288
sagarpatel288 / doSomething.kt
Created June 5, 2020 02:43
A normal function
fun doSomething(name: String) {
println("Name from the method doSomething is: $name")
}
@sagarpatel288
sagarpatel288 / letDefinition.kt
Created June 5, 2020 02:31
The definition of a scope function: let
public inline fun <T, R> T.let(block: (T) -> R): R {
/*...*/
return block(this)
}
@sagarpatel288
sagarpatel288 / getEvenOrNull.kt
Created June 5, 2020 02:26
Get even or null
private fun getEvenOrNull(randomNumber: Int): Int? =
if (randomNumber.rem(2) == 0) randomNumber else null
@sagarpatel288
sagarpatel288 / withDefinition.kt
Created June 5, 2020 02:23
The definition of a scope function: with
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
 /*…*/
 return receiver.block()
}
@sagarpatel288
sagarpatel288 / callFt.kt
Created May 8, 2020 02:08
Calling a higher order function where a function type has no parameter
/**
* 5/8/2020
* A function type without any parameter
* <p>
* if the higher order function has only one function type parameter and the function type has no parameter,
* We can simply write our business logic between curly parentheses right after the name of the function.
* </p>
* @author srdpatel
* @since 1.0
*/
@sagarpatel288
sagarpatel288 / ftWithoutParam.kt
Created May 8, 2020 02:05
A function type without any parameter
//region A function type that has no parameter
private fun doSomethingY(ft: () -> String) {
/*...*/
}
//endregion