Shouldn't this fail at compilation? or does return...
# getting-started
s
Shouldn't this fail at compilation? or does return default to false?
Copy code
val list = listOf( 1, 2, 3, 4, 5 )
    val evenList = list.filter {
        return
        it % 2 == 0
    }
v
It fails on compilation
return
is not allowed there
s
isn't filter a inline function?
and the lambda that it takes is not marked as crossinline
v
It is so
s
it compiles fine for me, the inlined return just returns from the nearest fun (happens to be main in my case )
v
That lambda travels into
if
condition inside
filterTo
function
s
what kotlin compiler are you using?
yes and filterTo is as well inlined
v
Kotlin 1.2.71
If it is inlined, so it must look like
if (return; it % 2 == 0)
. Even I would fail here
s
I'm on 1.2.71 as well, compiles fine
and as expected it just returns from the nearest function
v
Mayhap, it's another
list
with some other implementation of
filter
?
s
No, it just takes me to the one in stdlib collections
v
Strange, but it does not compile for me
s
yeah that is weird
v
Maybe some annotations that may affect `inline`s?
s
Try this, what do you get?
Copy code
inline fun testReturn( block : ()  -> Unit ) {
    block()
}

fun main( argv : Array<String> ) {

    testReturn {
        println( "setup" )
        return
        println( "complete" )
    }
}
v
Only the last
println
is unreachable, the rest is fine
s
yup and the return is a non-local return here
if you remove inline keyword, you should get a compilation error saying "return not allowed here"
v
Yes, it says so
s
and that is the same behavior with filter case too
so i'm not sure why you get a compilation error with an inlined filter
v
BTW, not everywhere, in a clean file it does, trying to figure out why it shows different behavior
s
hmm, that is strange
v
Try to put that fragment into a a block, where it will not be able to resolve
return
, e.g.:
Copy code
val block = {
   val list = listOf( 1, 2, 3, 4, 5 )
    val evenList = list.filter {
        return
        it % 2 == 0
    }
}
s
Gotcha
v
I think that happens, 'cause compiler resolves
return
of the function outside
filter
s
Here the block could be executed in another context
it is a lambda that could be passed to a thread for instance
Copy code
fun main( argv : Array<String> ) {

    val block = {
        val list = listOf( 1, 2, 3, 4, 5 )
        val evenList = list.filter {
            it % 2 == 0
        }
        return
        println( evenList )
    }

    thread {
        block()
    }
}
v
Oh, yes, I used it inside a class
s
Cool
v
Copy code
class MyClass {
  val block = {
    ...
  }
}