Typed In Source Code Incorrectly - Employee Class

This the code I’ve typed it and have problems with. I’ve included a copy of the original as well as what I’ve typed in.
This is the code I’ve typed in:

class Company( val name: String) {
private val departments: ArrayList = arrayListOf()
operator fun plusAssign(department: Department) {
departments.add(department)
}
operator fun minusAssign(department: Department) {
departments.remove(department)
}
val allEmployees: List
get() = arrayListOf().apply { departments.forEach{ addAll(it.employees)} }
}

This is the code that is a copy of the original:

class Company(val name: String) {

private val departments: ArrayList = arrayListOf()

val allEmployees: List
get() = arrayListOf().apply {
departments.forEach { addAll(it.employees) }
sort()
}

operator fun plusAssign(department: Department) {
departments.add(department)
}

operator fun minusAssign(department: Department) {
departments.remove(department)
}

}
The problem I’ve having problem with is the line that declares get() property for the company class. The look exactly the same to me but I’m sure I’ve typed it in correctly, for some reason I can’t type in sort() function. IntellijIDEA does not recognise it.

Sorry I meant incorrectly

Please help.

Please format your code properly by surrounding your code in triple backticks ```
like this:
```
// code goes here
```

// code goes here

Here is the code that I typed in:

class Company( val name: String) {
    private val departments: ArrayList<Department> = arrayListOf()
    operator fun plusAssign(department: Department) {
        departments.add(department)
    }
    operator fun minusAssign(department: Department) {
        departments.remove(department)
    }
    val allEmployees: List<Employee>
    get() = arrayListOf<Employee>().apply { departments.forEach { addAll(it.employees)} }
}

Here is the code that I downloaded:

Sorry, took me a few tries.
class Company(val name: String) {

  private val departments: ArrayList<Department> = arrayListOf()

  val allEmployees: List<Employee>
    get() = arrayListOf<Employee>().apply {
      departments.forEach { addAll(it.employees) }
      sort()
    }

  operator fun plusAssign(department: Department) {
    departments.add(department)
  }

  operator fun minusAssign(department: Department) {
    departments.remove(department)
  }

}

What do you try to achieve? Sort a list of employees after creating it?

Also, this original code you found isn’t really good for learning. It is not of good quality.

1 Like

Yes, sort the employees alphabetically. It’s nothing amazing, I had better chapters.

Then I say: screw this original code and do it properly:

val allEmployees: List<Employee>
    get() = departments.flatMap { it.employees }
        .sortedBy { it.name }

name is just an example, I don’t know what are props of Employee.

1 Like

Thanks.

Doesn’t work. Sorry, I told a lie, I thought the code was okay.

Call it peer pressure.

Sorry, I mislead you.