Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function type with receiver in Scala

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?

like image 704
Sol Avatar asked Jan 29 '16 11:01

Sol


People also ask

What is a receiver type?

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.

What is the meaning of => in scala?

=> 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 .

What is return type in scala?

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.

What is Lambda receiver?

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 .


1 Answers

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).

like image 58
Alexey Romanov Avatar answered Sep 19 '22 05:09

Alexey Romanov