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)
- signature should be either
def filterSitesById(sites: TargetingorfilterSitesById(sites: Seq[String]]), indeed there is noTargeting[Seq[String]]type - 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 intoBoolean), if it’sfoldLeftthen the lambda should combineBooleanresult withString, if it usesexists… any manual folding is unnecessary