How to call a method n times in Scala?

后端 未结 5 1027
轮回少年
轮回少年 2021-02-18 23:04

I have a case where I want to call a method n times, where n is an Int. Is there a good way to do this in a \"functional\" way in Scala?

case class Event(name: S         


        
5条回答
  •  情话喂你
    2021-02-18 23:47

    A more functional solution would be to use a fold with an immutable queue and Queue's fill and drop methods:

     val queue = lst.foldLeft(Queue.empty[Option[BigDecimal]]) { (q, e) =>
       e.name match {
         case "supply" => q ++ Queue.fill(e.quantity)(e.value)
         case "sale"   => q.drop(e.quantity)
       }
     }
    

    Or even better, capture your "supply"/"sale" distinction in subclasses of Event and avoid the awkward Option[BigDecimal] business:

    sealed trait Event { def quantity: Int }
    case class Supply(quantity: Int, value: BigDecimal) extends Event
    case class Sale(quantity: Int) extends Event
    
    val lst = List(
      Supply(3, BigDecimal("39.00")),
      Sale(1),
      Supply(1, BigDecimal("41.00"))
    )
    
    val queue = lst.foldLeft(Queue.empty[BigDecimal]) { (q, e) => e match {
      case Sale(quantity)          => q.drop(quantity)
      case Supply(quantity, value) => q ++ Queue.fill(quantity)(value)
    }}
    

    This doesn't directly answer your question (how to call a function a specified number of times), but it's definitely more idiomatic.

提交回复
热议问题