Register Login

Define Complex Objects In Scala

Updated May 18, 2018

List of Complex Objects In Scala

To create a list of complex objects in Scala, follow the steps listed below. In this example, we will be creating a list of students. To create a list of students, you need a class. This is because you can only create a complex object of a student once you have a class of them.

How to define Complex Objects In Scala?

In this example, we will create a class with three parameters – roll number, name, and marks.

To create this class, type - case class Stud (rollno : Int, name : String, marks : Int).

2.To create the objects, type in the relevant values for each parameter.

In this example, type – val students = List(Stud(1,”Veena”,40),Stud(2,”Pooja”,80),Stud(3,”Nadeem”,60))

Run the code. The list will appear.

 

Create the list in Java:

Type – List<Student> students – new ArrayList <> ();

Type the relevant values for the parameters. In this example, we are using the same values as the ones used in Scala. Type:

  • students.add(new Student(1,”Veena”,40));
  • students.add(new Student(1,”Pooja”,80));
  • students.add(new Student(1,”Nadeem”,60));

To print the values, type –

For(Student s : students)
{
System.out.print.ln(s);
}

The list will be displayed at the bottom of the screen.

Note: If the list is not displaying correctly, follow the two string method to view it.

The main advantage of Scala over Java is that is you don’t have to use multiple lines of code. A single line of code can be used to perform different functions. For example, to print only a section of the list, you can use the following codes:

  • Val first = students.head
  • Val rest = students.tail

  • Val rest = students.tail.tail

  • Val rest = students.tail.head

Val toppers = students.filter(s => s.marks>=60)

Val parts = students.partition (s => s.marks.>60)


×