How to use function literals in Scala?
To create a list in Java, write the following lines of code and import the package.
public static void main (String[] orgs)
{
List<Integer> nums = new ArrayList<>();
nums add(4);
nums add(8);
}
You can also do it another way if you are aware of the values, is by using the Arrays.aslist() option.
public static void main(String[] orgs)
{
List<Integer> nums = Arrays.aslist (4,7,2,3)
Creating a list of values in Scala
To create a list in Scala, you don’t have to use any new keywords. Simply use the list() option. Here ‘nums’ by default is an integer type.
var nums = List(4,7,2,3) //> nums : List[Int] = List(4, 7, 2, 3)
In java, you can use a normal for loop to create a list.
for(int { : nums)
{
System.out.println(N):
In Scala you don’t need a colon (like in Java), you only specify ‘nums’ and a left arrow as shown below.
for(int { : nums)
{
System.out.println(N):
Using Lambda expression in Java and Scala
In Java, you can use the forEach function for the lambda expression.
List<Integer> nums = Arrays.aslist(4, 7, 2, 3);
num.forEach(i -> System.out.println(i))
The symbol is slightly different in Scala, also you can specify the value of ‘I’.
nums.foreach { i:Int => println(i) }