Recent Posts

Functions in Python

Functions are named blocks of code that are designed to do one specific job. When you want to perform a particular task that you’ve defined in a function, you call the name of the function responsible for it. If you need to perform that task multiple times throughout your program, you don’t need to type all the code for the same task again and again; you just call the function dedicated to handling that task, and the call tells Python to run the code inside the function.

In Python, you define a function using the def keyword. Here is an example:

def greet_user():
“””Display a simple greeting.”””
print(“Hello!”)

The first line that ends in a colon is known as the function definition. The indented lines that follow the function definition make up the function body.

The second line of code is know as a docstring. A docstring is a comment, which in this example describes what the function does. Docstrings are enclosed in triple quotes, which Python looks for when it generates
documentation for the functions in your programs.

When you want to use this function, you call it. A function call tells Python to execute the code in the function. To call a function, you write the name of the function, followed by any necessary information in
parentheses, as shown below:

greet_user()

The call to the greet_user() function prints Hello!

Here is the complete code (function definition along with function call):

def greet_user():
“””Display a simple greeting.”””
print(“Hello!”)

greet_user()

Java SE8 Lambda Expressions

Java lambda expressions provide a means to represent anonymous methods using expressions.

A lambda expression is typically inserted where a reference to an instance of a class that implements an interface is expected.

Prior to Java SE8, programmers had to supply an instance of an anonymous inner class where an instance of a class that implements an interface was required. This obviously made the code cumbersome. Lambda expressions provide an easy way to accomplish the same thing with much less code.

The general syntax of a lambda expression is

(parameter list) -> expression

or

(parameter list) -> { statements }

The left side of the arrow (->) has the list of parameters of a method that the compiler will create in a class that implements the required interface.

The right side of the arrow has the body of the method. The curly braces are optional if the body of the method has only one line of code.

If there is only one parameter whose target type can be inferred by the compiler, then the parentheses on the left side can be omitted.

Here is an example: s -> { return s.length(); }

This assumes that the method is one whose expected parameter is a string. If an interface requires a method whose single parameter is a string, the above lambda expression could be supplied where an instance of a class that implements that interface is expected.

Suppose we have the following class code from Java SE7 or an earlier version:

public class ButtonFrame1  {
public ButtonFrame1() {

super(“Named Inner Classes”);

button1.addActionListener(new ColorChanger(Color.BLUE));    button2.addActionListener(new ColorChanger(Color.GREEN));    button3.addActionListener(new ColorChanger(Color.RED));

setVisible(true);

}

//private inner class that implements ActionListener

private class ColorChanger implements ActionListener {

private Color bgColor;

public ColorChanger(Color bgColor) {

this.bgColor = bgColor;

}

@Override    public void actionPerformed(ActionEvent event) {    contentPane.setBackground(bgColor)

}

}}

Since the following line of code expects and instance of a class that implements the action listener interface, the old Java SE7 or earlier code instantiates such a class and passes it to the addActionListener method.

button1.addActionListener(new ColorChanger(Color.BLUE));

In Java SE8, we don’t have to create the ColorChanger class because the compiler can do that for us if we replace the following code

new ColorChanger(Color.BLUE)

with the following lambda expression

event -> contentPane.setBackground(Color.BLUE)

The compiler will create a class similar to ColorChanger that implements the ActionListener interface. It knows to implement the ActionListener interface because that is the type of “argument” that button1.addActionListener( “argument” ) is expecting.

The compiler will create a class that has a method called actionPerformed whose argument is

event

and whose body is

contentPane.setBackground(Color.BLUE)

Notice how these are the expressions to the left and right of the arrow

event -> contentPane.setBackground(Color.BLUE)

Our original class could, therefore, be rewritten as

public class ButtonFrame1  {

public ButtonFrame1() {
super(“Lambdas”);
button1.addActionListener(event -> contentPane.setBackground(Color.BLUE));
button2.addActionListener(event -> contentPane.setBackground(Color.GREEN));
button3.addActionListener(event ->contentPane.setBackground(Color.RED)
}
}

As you can see, this code is much more concise since we did not have to write the ColorChanger class.

 

Lambda Expression Syntax Examples

Lambda Expression                                                              Notes

(Double d1, Double d2) -> { return d1*d2 } Full syntax is used here
(Double d1, Double d2) -> d1*d2 Curly braces and the return keyword are optional for single statements in the body
(d1, d2) -> { return d1*d2 } If the target types can be inferred based on the context, then the target types are optional
(String s) -> { return s.length() } Parenthesis are required with an explicit target type (ie. When you specify the data type of the argument)
(a, b) -> {int i = 5; int j=10; if (a > b) {return i} else { return j;}) The body may include multiple statements
( ) -> 12 some methods have no parameters, so no target type is required. For example, methods in the Runnable and Callable Functional Interfaces are abstract with no parameters.