fun foo() : Int {
val list = hashSetOf(1, 2)
list.forEach { x ->
if(true)
return x
}
return 5
}
It does not compile and creates the error "return not allowed here", which refers to the line "return x". Is this the way it is or am I doing something wrong? Am using Kotlin 0.5.75.
Here is some Smalltalk code that defines a class Foo with a method bar:
Object subclass: #Foo
bar
| list value |
list := OrderedCollection new add: 1; add: 2; add: 3; yourself.
value := list do: [ :each |
Transcript show: each printString.
true ifTrue: [^each].
].
^5.
Now I call Foo.bar running this code:
Transcript show: Foo new bar printString.
It prints "11" to the Smalltalk Transcript window as expected. How do I do the same thing in Kotlin? By the way, the Kotlin code below also does not compile. The error message is "break and continue are only allowed inside a loop".
public class Foo {
fun bar() : Int {
val set = hashSetOf(1, 2)
set.forEach { x ->
if(true)
break
}
return 5
}
}
Thanks for the answer. I was told that there is a workaround in Groovy:
def list =[1,2,3]def value = list.findResult { each ->
println(each)if(each)return each
return5}
println(value)
The code above then prints "11". Would that kind of workaround be possile in Kotlin as an intermediate solution till Kotlin turns 1.0? I'm starting to be a nuisance, I know ... ;-).
what I don’t really understand is why it is possible to do a return from inside the closure provided to the all iterator, but not in case of the forEach iterator. So the issue does not depend on closures? I’m a bit confused here …
So Scala implements non-local returns through throwing exceptions as also suggested by bashor in his last post. That is a little disappointing … Maybe it’s a JVM limitation all languages have to live with?
Unfortunately yes -- it's JVM limitation.
But I dont sure that the implementation with exceptions(like in Scala) is best solution. It necessary to investigate.