https://kotlinlang.org logo
#announcements
Title
# announcements
i

Ifvwm

07/21/2019, 3:08 PM
Copy code
fun counter():()->Int{
 var c=0
 fun g():Int{
  c++
  return c
 }
 return g
}
why “Function invocation g() expected”?
m

mbonnin

07/21/2019, 3:09 PM
I guess you need to declare g a val ?
Copy code
val g: (() -> Int) = {
   c++
   c
}
d

Dominaezzz

07/21/2019, 3:09 PM
Try
return ::g
?
i

Ifvwm

07/21/2019, 3:10 PM
but g is a function, I cannot return a function?
ok, ::g is ok, weird syntax, why it shouldn’t be like return variable?
d

Dominaezzz

07/21/2019, 3:13 PM
g
isn't a variable. To return it like a variable you have to do what @mbonnin described.
m

mbonnin

07/21/2019, 3:13 PM
You need an instance of a function type. It's explained there: https://kotlinlang.org/docs/reference/lambdas.html#instantiating-a-function-type
i

Ifvwm

07/21/2019, 3:33 PM
Copy code
val counter:()->()->Int = {
 var c=0
 val g = {
  c++
  c
 }
 g
}
d

Dominaezzz

07/21/2019, 3:34 PM
Copy code
val counter:()->()->Int = {
 var c=0
 {
  c++
  c
 }
}
🙂
i

Ifvwm

07/21/2019, 3:35 PM
wow
k

Kroppeb

07/21/2019, 6:04 PM
isn't
c++;c
equal to
++c
d

Dominaezzz

07/21/2019, 6:06 PM
True
Copy code
val counter:()->()->Int = {
 var c=0
 {
  ++c
 }
}
2 Views