mcy
mcy

Reputation: 89

Question about convert List of string to case class

I have two types of List[String], List("1234:abcd") and List("1234:*"), I want to convert these list of string to "case class FeatureWhitelisting", "byName" means whitelisting has name ("abcd"), "ALL" means no name (" * ").

sealed trait myWhitelisting

    object myWhitelisting {
      case class ByName(name: String) extends myWhitelisting
      case object All extends myWhitelisting
  }

  case class FeatureWhitelisting(accountId: String, whitelisting: myWhitelisting)

right now I have this, what should be the second parameter? ]

list.map(acct => FeatureWhitelisting(acct.split(":")(0), ))

Upvotes: 0

Views: 88

Answers (2)

User9123
User9123

Reputation: 1733

you can use pattern matching:

List("1234:abcd", "1234:*")
  .map { str =>
    str.split(":") match {
      case Array(accountId, "*") => FeatureWhitelisting(accountId, All)
      case Array(accountId, name) => FeatureWhitelisting(accountId, ByName(name))
    }
  }
  .foreach(println(_))

Upvotes: 2

Charlie Flowers
Charlie Flowers

Reputation: 1380

I hope I'm not missing any nuance here, but would

list.map{acct => 
      val myVals = acct.split(":").padTo(2, "*")
      FeatureWhitelisting(myVals(0), myVals(1) match {
        case "*" => myWhitelisting.All
        case s => myWhitelisting.ByName(s)
      }
  )
}

do the job?

Upvotes: 1

Related Questions