mitrakov

Foldable pattern

Aug 10th, 2020
1,288
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * The catamorphism for the JSON value data type.
  3.  */
  4. final def fold[X](
  5.   jsonNull: => X,
  6.   jsonBoolean: Boolean => X,
  7.   jsonNumber: JsonNumber => X,
  8.   jsonString: String => X,
  9.   jsonArray: Vector[Json] => X,
  10.   jsonObject: JsonObject => X
  11. ): X = this match {
  12.   case JNull       => jsonNull
  13.   case JBoolean(b) => jsonBoolean(b)
  14.   case JNumber(n)  => jsonNumber(n)
  15.   case JString(s)  => jsonString(s)
  16.   case JArray(a)   => jsonArray(a)
  17.   case JObject(o)  => jsonObject(o)
  18. }
  19.  
  20. //usage:
  21. json.fold(
  22.   None,
  23.   boolValue => Some(s"This is boolean: $boolValue"),
  24.   numberValue => Some(s"This is integer: ${numberValue.toInt}"),
  25.   _ => None,
  26.   _ => None,
  27.   _ => None,
  28. )
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×