Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
How to use function receiver type with SAM interfaces in Kotlin

I'm coming from Java and am new to Kotlin. I try to understand how to use receiver type with lambdas specified as functional SAM interfaces.

Let the code speak for itself.

fun interface Delegator <T> {
    fun delegate(receiver: T)
}

fun <T> invokeWithDynamicReceiver(receiver: T, fn: T.() -> Unit) = receiver.fn()
fun <T> invokeWithSamInterface(receiver: T, fn: Delegator<T>) = fn.delegate(receiver)

fun dynamicReceiver() {
    invokeWithDynamicReceiver("Foo") { length } // Dynamic receiver
    invokeWithSamInterface("Foo") { it.length } // Can't bind receiver as "this"
}

How do I need to change the code to use the Delegator lambda with dynamic receiver?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can define the functions inside the Delegator as extension function, this way the receiver is passed as this to the lambda.

fun interface ExtensionDelegator <T, R> {
    fun T.delegate(): R
}

fun <T, R> invokeWithExtensionSamInterface(receiver: T, fn: ExtensionDelegator<T, R>): R =
    with(fn) { receiver.delegate() }

Alternatively, you can simply define the dynamic receiver with a typealias to achieve the same result.

typealias AliasDelegator<T, R> = T.() -> R

fun <T, R> invokeWithAliasSamInterface(receiver: T, fn: AliasDelegator<T, R>): R = fn.invoke(receiver)

On the use site, both approaches look the same.

fun main() {
    val result = invokeWithExtensionSamInterface("Foo") { length }
    println(result)

    val otherResult = invokeWithAliasSamInterface("Fizz") { length }
    println(otherResult)
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!