We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.
Nope, that's the point of the article.
greet is of type String.() -> Unit
That means that greet is a function that wait for a String and return Unit (void...)
And it's initialized with
{ println("Hello $this") }
so greet("txt") will print out "Hello txt"
https://uploads.disquscdn.c...
"greet is a function that wait for a String and return Unit" i don't get this
(String)->Unit is a function that wait for a String and returns a Unit
String.()->Unit is a function with no parameters that has to be called on a String and returns a Unit
You make a parallelism with the apply that wants a T.()->Unit in fact you call:
OBJECT.apply { ... }
if you try to call OBJECT.apply { paramObject -> ... } an error is warned
(the let or also wait for a (T)->Unit/T in fact you can hav OBJECT.let{ param -> ... }
so, imho the correct form to call a val greet : String.() -> Unit is: "Stringa".greet()
and the correct form to call a val greet : (String)->Unit is: greet("Stringa")
by the way you can still call val greet : String.() -> Unit like this greet("Stringa"), but i think is only a "secondary way"
For conclusion, a question:
if you call greet of your example like greet("txt")
where is the difference between a (String)->Unit and a String.() -> Unit
?
Well, at start it also confused me. But after a little test, it appears that the way he defined functions allow him to use the string parameter as if it is the object holding the function (an inline extension). I mean, if we change greet andd countChars to (String) -> Unit, we have to use "it" to access parameter's properties :
```
val greet: (String) -> Unit = { println("Hello $it") }
val countChars: (String) -> Unit = { println("Counted chars: ${it.length}") }
```
Hi, when you talk about "Function Literals with Receiver" in the example you write:
greet(txt)
countChars(txt)
Shouldn't be the following?
txt.greet()
txt.countChars()
Thanks