scalaakka

Scala fold function to detect occurrence of a value in Seq[String]


I'm trying to write a scala function to detect whether a site id (site_id) exists within a sequence of targeted site ids (targetedSiteIds).

If the site id exists in the Seq, the function filterSiteById returns true, else it returns false.

However, the code below keeps giving me the error error: Targeting does not take type parameters.

Could you help me fix this issue?

Thanks in advance!


val site_id = "0011a522ce0f4bbbbaa6b3c38cafaa0f"

targeting = Targeting(targetedSiteIds=Seq("0009a522ce0f4bbbbaa6b3c38cafaa0f","0010a522ce0f4bbbbaa6b3c38cafaa0f","0011a522ce0f4bbbbaa6b3c38cafaa0f") // TargetedSiteIds)

case class Targeting(targetedSiteIds: Seq[String])

var trueOrFalse=filterSitesById(targeting) // true or false

def filterSitesById(sites: Targeting[Seq[String]]): Boolean = {
  sites.fold(false)(_.exists(_.idx==site_id))
}


Solution

  • case class Targeting(targetedSiteIds: Seq[String])
    
    val site_id = "0011a522ce0f4bbbbaa6b3c38cafaa0f"
    
    val targeting = Targeting(targetedSiteIds = Seq("0009a522ce0f4bbbbaa6b3c38cafaa0f","0010a522ce0f4bbbbaa6b3c38cafaa0f","0011a522ce0f4bbbbaa6b3c38cafaa0f"))
    
    def filterSitesById(sites: Targeting): Boolean = {
      sites.targetedSiteIds.exists(_ == site_id)
    }
    
    filterSitesById(targeting)
    
    1. signature should be either def filterSitesById(sites: Targeting or filterSitesById(sites: Seq[String]]), indeed there is no Targeting[Seq[String]] type
    2. code inside the function was wrong as well - if it's fold, then it would only combine results into the same type (Seq[String] cannot be folded into Boolean), if it's foldLeft then the lambda should combine Boolean result with String, if it uses exists... any manual folding is unnecessary