简体   繁体   中英

pass anonymous function as a parameter

I am new to Scala. I import function from another JVM language and helper shows me this signature

在此处输入图片说明

It confuses me. In the original language I designed that function to work like this

dsl {
   method { }
   header { }
}

But how it will look like in Scala?

In another language the dsl looks like this

class GRLMessageDSL : GRLMessage() {

    fun dsl(closure: GRLMessageDSL.() -> Unit) : GRLMessage {
        closure()
        return this
    }

    fun method(closure: GRLMessageDSL.() -> GRLProtocol.GRLMethod) : GRLMessage {
        methodType = closure()
        return this
    }

    fun headers(closure: GRLMessageDSL.() -> Unit) : GRLMessage {
        closure()
        return this
    }

    fun header(closure: GRLMessageDSL.() -> Pair<String, String>) : GRLMessage {
        headerMap += closure()
        return this
    }

    fun multipart(closure: GRLMessageDSL.() -> IGRLMultipart) : GRLMessage {
        multipartObject = closure()
        return this
    }

Anonymous function or lambda with one input parameter gets compiled to Function1 interface in Scala thats why you see Function1

That means

val f = {x: Int => x * x } (this is just syntactic suger)

the above function is equivalent to (in fact compiled to)

new Function1[Int, Int] { def apply(x: Int) = x * x }

Scala REPL

scala> val f = {x: Int => x * x }
f: Int => Int = <function1>

scala> new Function1[Int, Int] { def apply(x: Int) = x * x }
res1: Int => Int = <function1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM