I'm investigating this Kotlin example:
class HTML {
fun body() { ... }
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML() // create the receiver object
html.init() // pass the receiver object to the lambda
return html
}
html { // lambda with receiver begins here
body() // calling a method on the receiver object
}
I'm wonder how to write this code in scala? How to declare in scala function type with receiver?
the receiver type is the type an extension function extends. the receiver object is the object an extension function is called on; the this keyword inside the function body corresponds to the receiver object.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
If you don't specify any return type of a function, default return type is Unit which is equivalent to void in Java. = : In Scala, a user can create function with or without = (equal) operator. If the user uses it, the function will return the desired value.
A lambda is a way to define behavior similar to a regular function. A lambda with a receiver is a way to define behavior similar to an extension function. To understand the purpose of lambdas with receivers, consider the following example function that creates and returns a Button .
There is no equivalent to this in Scala. You'd simply use a function which takes HTML
as an argument (possibly as an implicit argument, but this isn't reflected in the type and unlikely in this case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With