Lambda expressions

A lambda expression is an anonymous function that is not declared but passed immediately as an expression.

Let's go ahead and make use of lambda expressions in our TicTacToe app. Open MainActivity.kt. In the startNewGame() function, replace the following lines of code:

cell.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
cellClickListener(i, j)
}
})

Replace them with this line of code:

cell.setOnClickListener { cellClickListener(i, j) } 

In the previous lines of code, we have an anonymous object that is implementing a Java interface that has a single abstract method (onClick()). All of this can be replaced with a simple lambda expression.

A Single Abstract Method (SAM), as it is often called, refers to the functional method in an interface. The interface typically contains only one abstract method that is known as SAM or a functional method.

Now, build and run to see the state of the app:

Let's go ahead and make use of all we've learned so far to in order complete work on the game.

Android Studio provides a default tool chain that supports most of the JAVA 8 features, including lambda expressions. It is highly recommended that you use the default tool chain and disable all other options such as jackoptions, and retrolambda.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset