-2

I have a case class as

case class Attendance(List(name,totalDay))

and i have three variable

val ana = 0
val mario = 33
val romero = 11

I have to create the object of attendance class such as they have name and attendance only if attendance is greater than zero like for above i should have

Attendance((Mario,33),(Romero,12))
  • 1
    Just a quick tip: To avoid hurting your eyes, name variables / vals using lower-camel-case (e.g. `myVariable`) and types (like case classes) using upper-camel-case (e.g. `MyCaseClass`). – Markus Appel Apr 11 '19 at 15:11

1 Answers1

5

Your code is not only very far from what's considered best practice in Scala in terms of variable and class naming, but also has inconsistencies:

At first, you show the code snippet:

// --- WRONG --- //
val Ana = 0
val Mario = 33
val Romero = 11

And then you show the code snippet

// --- WRONG --- //
Attendance((Mario,33),(Romero,12))

The problem is that in this situation, (Mario, 33) just means (33, 33), because Mario is a variable that you assigned to be 33. What you should do instead is:

val ana = ("Ana", 0)
val mario = ("Mario", 33)
val romero = ("Romero", 11)

Another inconsistency is

// --- WRONG --- //
case class attendance(List(name,totalDay))

This would not compile. When writing List(name, totalDay) you define a List containing two elements, name and totalDay. These elements are not defined in your example.

What you want to do instead is:

case class Attendance(attendees: List[(String, Int)])

What does attendees: List[(String, Int)] mean?

It means that you define a parameter to your case class Attendance, and this parameter is called attendees, and is of type List[(String, Int)] (speak: "A list of tuples, each consisting of a string and an integer")

Then you can use it:

val listOfAttendees: List[(String, Int)] = ??? // Not implemented yet
val attendance = Attendance(listOfAttendees)

But how do you make listOfAttendees?

The answer is filter:

val allAttendees = List(ana, mario, romero)
val filteredAttendees = allAttendees.filter {
   case (name, days) => days > 0
}

Put it all together:

val ana = ("Ana", 0)
val mario = ("Mario", 33)
val romero = ("Romero", 11)

case class Attendance(attendees: List[(String, Int)])

val allAttendees = List(ana, mario, romero)

val filteredAttendees = allAttendees.filter {
   case (name, days) => days > 0
}

val attendance = Attendance(filteredAttendees)

Try it out!


I hope this helps.

Markus Appel
  • 3,138
  • 1
  • 17
  • 46
  • Thanks for you help, Sorry for the inconsistency in my code. As i wrote pseudo code (will keep a note of writing better one if must). However your code worked like charms, Thanks a lot again –  Apr 11 '19 at 17:06
  • @devD Can you accept the answer if it was helpful to you? – Markus Appel Apr 26 '19 at 12:59
  • @devD Please accept the answer if it is helpful to you. – Markus Appel May 13 '19 at 11:43