Skip to main content

Kotlin Returns and Jumps

Returns and Jumps

Kotlin has three structural jump expressions:
  • return. By default returns from the nearest enclosing function or anonymous function.
  • break. Terminates the nearest enclosing loop.
  • continue. Proceeds to the next step of the nearest enclosing loop.
All of these expressions can be used as part of larger expressions:
val s = person.name ?: return
The type of these expressions is the Nothing type.

Break and Continue Labels

Any expression in Kotlin may be marked with a label. Labels have the form of an identifier followed by the @ sign, for example: abc@, fooBar@ are valid labels (see the grammar). To label an expression, we just put a label in front of it
loop@ for (i in 1..100) {
    // ...
}
Now, we can qualify a break or a continue with a label:
loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}
A break qualified with a label jumps to the execution point right after the loop marked with that label. A continue proceeds to the next iteration of that loop.

Return at Labels

With function literals, local functions and object expression, functions can be nested in Kotlin. Qualified returns allow us to return from an outer function. The most important use case is returning from a lambda expression. Recall that when we write this:
fun foo() {
    ints.forEach {
        if (it == 0) return
        print(it)
    }
}
The return-expression returns from the nearest enclosing function, i.e. foo. (Note that such non-local returns are supported only for lambda expressions passed to inline functions.) If we need to return from a lambda expression, we have to label it and qualify the return:
fun foo() {
    ints.forEach lit@ {
        if (it == 0) return@lit
        print(it)
    }
}
Now, it returns only from the lambda expression. Oftentimes it is more convenient to use implicits labels: such a label has the same name as the function to which the lambda is passed.
fun foo() {
    ints.forEach {
        if (it == 0) return@forEach
        print(it)
    }
}
Alternatively, we can replace the lambda expression with an anonymous function. A return statement in an anomymous function will return from the anonymous function itself.
fun foo() {
    ints.forEach(fun(value: Int) {
        if (value == 0) return
        print(value)
    })
}
When returning a value, the parser gives preference to the qualified return, i.e.
return@a 1
means "return 1 at label @a" and not "return a labeled expression (@a 1)".

Comments

Popular posts from this blog

Vertical AutoScrolling TextView in Android

In android by default we can scroll the text in horizontal using marquee in layout, but if we want to scroll the text in vertical its not possible by default. So here we will learn to create a custom TextView which will auto-scroll in vertical direction. Source Code:  VerticalScrollingTextView-Android Create a AutoScrollingTextView.class which extends TextView: @SuppressLint ( "AppCompatCustomView" ) public class AutoScrollingTextView extends TextView { private static final float DEFAULT_SPEED = 65.0f ; public Scroller scroller ; public float speed = DEFAULT_SPEED ; public boolean continuousScrolling = true; public AutoScrollingTextView (Context context) { super (context) ; init( null, 0 ) ; scrollerInstance(context) ; } public AutoScrollingTextView (Context context , AttributeSet attrs) { super (context , attrs) ; init(attrs , 0 ) ; scr...

Flexbox inside the RecyclerView as a LayoutManager (FlexboxLayoutManager).

Currently google has release the Flexbox which can be used for building flexible layouts using FlexboxLayout, it can be interpreted as an advanced LinearLayout because both layouts align their child views sequentially. For more detail on this flexbox-layout But here we are gonna work on Flexbox with RecyclerView. Flexbox with a large number of items in a scrollable container! Let's first see what are the Supported attributes / features comparison Due to some characteristics of the RecyclerView, some Flexbox attributes are not available/not implemented to the FlexboxLayoutManager. Here is a quick overview of the attributes/features comparison between the two containers. Attribute / Feature FlexboxLayout                FlexboxLayoutManager (RecyclerView) flexDirection flexWrap (except wrap_reverse ) justifyContent alignItems alignContent - layout_order - layout_fle...

Android Customized-FloatSeekBar

A SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch the thumb and drag left or right to set the current progress level or use the arrow keys. Placing focusable widgets to the left or right of a SeekBar is discouraged. SeekBar support only int values for progress: void setMax(int max) Set the upper range of the progress bar max. void setMin(int min) Set the lower range of the progress bar to min. void setProgress(int progress) Sets the current progress to the specified value. int getMax() Return the upper limit of this progress bar's range. int getMin() Return the lower limit of this progress bar's range. int getProgress() Get the progress bar's current level of progress. In some scenario we would need floating point seekbar progress, which is not supported by default in android. Here the floating seekbar which supports floating point value: You can download the full sample and library from https://github.com/yuvaraj119/Cus...