Return from outer function


#1

I have tried return from outer function:

fun s(x : Int) : Int{   var sn = 0;   fun s1()   {   sn += 1   if( sn > 3)            return@s 3   }   for (i in 1..x)   s1()   return sn }

But I have error: Error:(7, 13) Kotlin: 'return' is not allowed here

Why?
I don’t see big difference from example at http://confluence.jetbrains.com/display/Kotlin/Functions:

fun reachable(from : Vertex, to : Vertex) : Boolean {
  val visited = HashSet<Vertex>()
  fun dfs(current : Vertex) {
  // here we return from the outer function:
  if (current == to) return@reachable true
  // And here – from local function:
  if (!visited.add(current)) return
  for (v in current.neighbors)
  dfs(v)
  }
  dfs(from)
  return false // if dfs() did not return true already
}

#2

The docs are somewhat outdated. Non-local returns are not supported yet, and will probably never be supported for this case, only for inline functions.


#3

Is link to a discuss about this?

I think it is useful feauture for helper-functions.

I have tried inline function:

fun s(x : Int) : Int{
  var sn = 0;
  inline fun s1()
  {
  sn += 1
  if( sn > 3)
           return@s 3
  }
  for (i in 1…x)
  s1()
  return sn
}

fun main(args : Array<String>) {
  println(s(4))
}


but have error at line “inline fun s1()”:
Error:(7, 11) Kotlin: Unexpected tokens (use ‘;’ to separate expressions on the same line)


#4

As mentioned above, this feature is not yet implemented. To make a local function inline, surround "inline" by square brackets


#5

If I right understand the future (return from outer function) was in kotlin, then it was remove from the language.

Why it was remove?


#6

It was never implemented


#7

what about now?
since 3 years ago until now
is it implemented? because it could be very useful.


#8

Non-local returns are not on the table, but local inline functions are. You are welcome to add your use-case here: https://youtrack.jetbrains.com/issue/KT-17579