Higher Order Functions in Kotlin

I am going to use the following function to get the job done

private fun getImage(view: View) {
val image = view.drawToBitmap()
ApplyFiltersAndStoreImage(
mContext,
"Example.jpg",
image)
.subscribeOn(schedulers.Computation()) // computation thread
.observeOn(schedulers.ui())
.subscribe({
shareImage(it) // function which shares the image
}, {
}
).addTo(disposables)
}
  1. I could write the same image generation function twice to perform different actions.
  2. I could use the same function and rather than writing it twice I could pass the type of action it should perform after image is generated i.e apply conditions on the type to check whether to share the image or to display the image as a notification.

What are Higher Order Functions ?

fun higherOrderFunc(block: () -> Unit) 
{
block() //invokes the expression
}

Lambda functions

a) val sum = { x:Int, y:Int -> println(x + y) } // without optional paramsb) val sum: (Int, Int) -> Unit = { x: Int, y: Int -> println(x + y)} // with optional params

Passing lambda expression as a parameter to Higher-Order Function which returns a Unit

private fun functionA(view: View) {
getImage(view)
{location->
//do your stuff
}
}
private fun functionA(view: View) {
getImage(view, actionOne) // actionOne is our lambda function
}
val actionOne = {it:String->
// do your stuff
}
private fun functionA(view: View) {
getImage(view)
{location->
ShareImage(location)
}
}

private fun functionB(view: View) {
getImage(view)
{location->
openNotification(location)
}
}
private fun functionC(view: View) {
getImage(view)
{location->
sendImageToServer(location)
}
}
private fun getImage(view: View, block: (it: String) -> Unit) {
val image= view.drawToBitmap()
ApplyFiltersAndStore(
mContext,
"example.jpg",
image
)
.subscribeOn(schedulers.Computation())
.observeOn(schedulers.ui())
.subscribe({
block.invoke(it) // or block(it)
}, {

}
).addTo(disposables)
}
private fun getImage(view: View, block: (it: String) -> Unit) {
val image= view.drawToBitmap()
ApplyFiltersAndStore(
mContext,
"example.jpg",
image
)
.subscribeOn(schedulers.Computation())
.observeOn(schedulers.ui())
.subscribe({
block.invoke(it)
}, {

}
).addTo(disposables)
}
block: (it: String) -> Unit 
block.invoke(it)
{location->
ShareImage(location)
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store