2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

return return ...

Posted at

return return

warning: unreachable code だと?

warning: unreachable code

などという出力があって焦ったわけです

$ kotlinc main.kt
main.kt:16:5: warning: unreachable code
    return return inc(value)
    ^

Kotlinだからエラーにはならないのか、そうか。ただ、期待した通りの動作になるのかどうか不安なのでちょっと調べることに。

return return するとどうなるのか

とりあえず、実際の動作としては以下の通りで、まぁ動作としては期待通りな訳ですが。

>>> fun inc(value: Int): Int {
...     return value.inc()
... }
>>> fun returnInc(value: Int): Int {
...     return inc(value)
... }
>>> fun returnReturnInc(value: Int): Int {
...     return return inc(value)
... }
>>> inc(1)
res9: kotlin.Int = 2
>>> returnInc(1)
res10: kotlin.Int = 2
>>> returnReturnInc(1)
res11: kotlin.Int = 2

Kotlinにおける return

return by default returns from the nearest enclosing function or anonymous function
...
All of these expressions can be used as part of larger expressions

Returns and jumps | Kotlin

探してみるとStack Overflow にも参考になる投稿があった。

java - Why can "return" return a "return" in Kotlin? - Stack Overflow

とはいえ意図せずにreturn returnしてしまうのは防ぎたいので、Linter辺りで処理させるのが良いのかな。

>>> fun rTRTRTTRTRTRRRTTTTRTRTRTRTRTRRRRInc(): Int {
...     return throw return throw throw throw return throw return return return 8
... }
>>> rTRTRTTRTRTRRRTTTTRTRTRTRTRTRRRRInc()
res3: kotlin.Int = 8
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?