user5436326
user5436326

Reputation:

kotlin Extension function don't get how this thing works

I am a very new on learning Kotlin . As far everything was quite understandable , By Today I have came across to a piece of code which intimidate me . I have searched a lot and did some research on this piece of code . here is this two extension function I need to understand

private fun T ?.useOrDefault(default: R, usage: T.(R) -> R) = this?.usage(default) ?:default

second one

inline fun <F, S> doubleWith(first: F, second: S, runWith: F.(S) -> Unit) {
   first.runWith(second)
  }

usage

a.useOrDefault(100) { getInteger(R.styleable.ArcSeekBar_maxProgress, it) } 
set(progress) { 
field = bound(0, progress, Int.MAX_VALUE) 
drawData?.let 
  { 
    drawData = it.copy(maxProgress = progress) } invalidate() 
   }

I have a basic understanding over lambdas and higher order function but this generics version of function is really out of my reach as a beginner

Thanks and appreciations in advance

Upvotes: 0

Views: 126

Answers (2)

user8320224
user8320224

Reputation: 228

doubleWith() convenient to use with object as first parameter, complex expression as second parameter and lambda as third, for example

doubleWith(first = a, second = {complex expression}) { 
    // first as this (like in with body)
    // and second as it (or explicit parameter name)
    // in lambda body
    ...
}

Upvotes: 0

Wubbalubbadubdub
Wubbalubbadubdub

Reputation: 2475

The main thing about both of this functions are , they are extension function according to official Doc

To declare an extension function, we need to prefix its name with a receiver type, i.e. the type being extended. The following adds a swap function to MutableList<Int>

fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}

The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot). Now, we can call such a function on any MutableList<Int>

Now if you want you can change the type Int to Generic Like this

fun <T> MutableList<T>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}

Now look at the funtion useOrDefault is taking the caller object ("a" in the example), and if it's not null, it runs the function "usage", otherwise it returns the default value. As usage is acting as an extension function of the caller, that's why it can do "this?.usage()"

read this article this will be very helpful to understand this function

Ninja Functions in Kotlin

Upvotes: 2

Related Questions