Home > Mobile >  From extension method to lambda with receiver, how?
From extension method to lambda with receiver, how?

Time:11-23


fun (String).capitalizeLast():String {
  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)

CodePudding user response:

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

CodePudding user response:

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.

  • Related