-2

As example, I have the following Scala class(and the same in C#, ofc):

import com.github.nscala_time.time.Imports._

class Flight{
  var FlDate:DateTime = new DateTime
  var Origin = ""
  var Destination = ""
}

flights = Flight[]

Original C# Code:

var rez = flights.SelectMany(p => new[] {
     new { Airport = p.Origin, IsOrigin = true },
     new { Airport = p.Destination, IsOrigin = false }
   })
   .GroupBy(x => x.Airport)
   .Select(g => new
   {
       Airport = g.Key,
       LeftCount = g.Count(x => x.IsOrigin),
       ArrivedCount = g.Count(x => !x.IsOrigin)
   });

Incorrect Scala code:

var rez = flights
  .flatMap(case (airport, isOrigin) => {
  new { airport = _.origin, isOrigin = true }, // issue - ?
  new { airport = _.destination, isOrigin = false } // issue - ?
})
.groupBy(_.airport)
.map {
  case (airport, leftCount, arrivedCount) => new {
    val airport = ??? // issue - g.Key?
    val leftCount = ??? // issue - g.Count(x => x.IsOrigin) ?
    val arrivedCount = ??? // issue - g.Count(x => !x.IsOrigin) ?
  }
}

So, as you see by the code, as result i need to have an array of objects with the following properties: ListBuffer[airport:String, leftCount :Int, arrivedCount:Int]

So...

  1. Can someone help to fix the code?
  2. Maybe, someone knows some good article about "syntax of work with anonymous objects in Scala" topic?
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101

1 Answers1

1

You can do:

val flights: Seq[Flight] = ...
// Let's represent the result in a Map[Airport, (Left, Arrived)]
val res: Map[String, (Int, Int)] = 
  flights
    .flatMap(flight => Seq((flight.origin, true), (flight.destination, false)))  // Seq[(String, Boolean)]
    .groupBy { case (airport, _) => airport }  // Map[String, List[(String, Boolean)]] 
    .mapValues { grouped =>
      val left = grouped.count { case (_, isOrigin) => isOrigin }
      val arrived = grouped.count { case (_, isOrigin) => !isOrigin }
      (left, arrived)
    }
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118