caeus
caeus

Reputation: 3696

From extension method to lambda with receiver, how?

class SomeClass{
  val logger = ...
  fun (String).capitalizeLast():String {
    logger.info("capitalizeLast called")
    return this.substring(0,this.length-1) + this.substring(this.length-1,this.length).toUpperCase()
  }
  val asLambda: (String).()->String = <<dark magic using the previously defined extension method??
}


I mean, I could always write


val asLambda: (String).()->String = {
  this.capitalizeLast()
}

But is there not a syntactic sugar using :: (as with ::println)

Upvotes: 1

Views: 392

Answers (2)

Arpit Shukla
Arpit Shukla

Reputation: 10493

There's a shorter way to capitalize the last character. You can do:

str.dropLast(1) + str.last().uppercase()

You can make a extension function out of it:

fun String.capitalizeLast() = dropLast(1) + last().uppercase()

Usage:

println("hello".capitalizeLast())

And you can refer to this function using String::capitalizeLast. Example:

val strings = listOf("hello", "world")
strings.map(String::capitalizeLast)

try it yourself

Edit: From your comment below, it seems to me that you want to capture a function, which has an argument as well as a receiver, in a variable. Take a look at the following example:

fun Int.addLongGiveDouble(num: Long): Double {
    return (this + num).toDouble()
}

fun main() {
    val lambda: Int.(Long) -> Double = Int::addLongGiveDouble
    val result: Double = 5.lambda(10L) // result is 15.0
}

Upvotes: 3

Tenfour04
Tenfour04

Reputation: 93531

Lambda is the wrong terminology here. Lambda is just a syntax alternative for a functional object. A functional object is not a lambda. You're trying to get a functional object out of the extension function.

It's the same for extension functions as for member functions:

val asFunctionObject: String.()->String = String::capitalizeLast

Note that String.() -> String and (String) -> String are effectively the same type. The distinction only matters when it's used as the type of a function parameter and affects how lambdas are parsed when lambda syntax is used with a higher-order function.

Upvotes: 2

Related Questions