简体   繁体   中英

how to convert class in scala into Algebraic Data Types?

Currently I have two classes, how to transfer them to Algebraic Data Types? I think I can do something like this case class BlacklistDynamoDBUpdate(ruleName: String, whitelistedAccount, featureName: String) , but how to use those method in that class?

class DynamoDBUpdateBlacklist {
  private var features: Array[BlacklistDynamoDBUpdate] = _

  def getFeatures = features

  def setFeatures(features: Array[BlacklistDynamoDBUpdate]) = {
    this.features = features
  }
}
class BlacklistDynamoDBUpdate {
  private var ruleName: String = _
  private var whitelistedAccount: String = _
  private var featureName: String = _

  def getFeatureName: String = featureName

  def setFeatureName(featureName: String) = {
    this.featureName = featureName
  }

  def getRuleName: String = ruleName

  def setRuleName(ruleName: String) = {
    this.ruleName = ruleName
  }

  def getWhitelistedAccounts: String = whitelistedAccount

  def setWhitelistedAccounts(whitelistedAccount: String): Unit = {
    this.whitelistedAccount = whitelistedAccount
  }
}

I transfer a json into scala object, json look like this

"features": [ { "featureName": "***", "ruleName": "***", "whitelistedAccounts": "***" }], 

what I want is get those attributes value

If you need to parse json into idiomatic scala code then use simple case classes and library that is design to parse such jsons directly into those case classes (personally I sugest this one https://lihaoyi.com/upickle or this one https://circe.github.io/circe ).

here is example code that shows how to use upickle.

import upickle.default.{ReadWriter => RW, macroRW}

final case class DynamoDBUpdateBlacklist(features:Seq[BlacklistDynamoDBUpdate])
final case class BlacklistDynamoDBUpdate(featureName:String, ruleName:String, whitelistedAccounts:String)

object DynamoDBUpdateBlacklist {
  implicit val rw: RW[DynamoDBUpdateBlacklist] = macroRW
}
object BlacklistDynamoDBUpdate {
  implicit val rw: RW[BlacklistDynamoDBUpdate] = macroRW
}

//use it like that
import upickle.default._
println(
  read[DynamoDBUpdateBlacklist]("""
    {"features":[{ "featureName": "***", "ruleName": "***", "whitelistedAccounts": "***" }]}
  """)
)

//DynamoDBUpdateBlacklist(Vector(BlacklistDynamoDBUpdate(***,***,***)))

https://scalafiddle.io/sf/8eqFEfX/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM