Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
78: Play JSON Library
When you're building APIs in Scala, you'll spend a huge amount of your time moving data between your strongly-typed case classes and the loosely-typed world of JSON. While there are several libraries out there, play-json is a staple because it strikes a great balance between automation and explicit control. I've always preferred it over some of the more "magical" libraries because when something goes wrong with your data mapping, the compiler usually tells you exactly why.
Defining our Book domain
Let's build a simple inventory system for a bookstore. I'll start by defining a Book case class. We need a few different types here—strings, a double for the price, and a list of tags—just to see how the library handles collections.
case class Book(title: String, author: String, price: Double, tags: List[String])
Now, we need a way to tell Scala how to turn this class into JSON (Writing) and how to turn JSON back into this class (Reading). In play-json, we use a Format, which is essentially a combination of Reads and Writes.
Letting the compiler do the heavy lifting
For most simple case classes, you don't want to write the mapping by hand. It's tedious and error-prone. Instead, I'll use the Json.format macro. This generates the boilerplate for us at compile time.
import play.api.libs.json._
implicit val bookFormat: Format[Book] = Json.format[Book]
// Now we can easily convert to JSON
val myBook = Book("The Pragmatic Programmer", "Hunt & Thomas", 45.00, List("Programming", "Career"))
val json = Json.toJson(myBook)
// Result: {"title":"The Pragmatic Programmer","author":"Hunt & Thomas","price":45.0,"tags":["Programming","Career"]}
By marking bookFormat as implicit, any function that needs to know how to handle a Book (like Json.toJson) will just find this formatter in the scope and use it. It's clean, and it works perfectly as long as your JSON keys match your case class field names exactly.
The "where is my data?" moment
Here is where I usually trip up when I'm moving fast. I tried to parse a JSON string coming from a mock API, and I wrote this:
val jsonString = """{"title": "Scala Guide", "author": "Expert", "price": 20.0, "tags": ["Scala"]}"""
val json = Json.parse(jsonString)
val book = json.as[Book] // I thought this was the way!
The problem? .as[T] is an "unsafe" method. If the JSON is slightly malformed—maybe a field is missing or a type is wrong—it throws a runtime exception. In a production app, crashing your entire request thread because a client sent a string instead of a double is a disaster. I realized I was treating the JSON as a guaranteed success rather than a possibility.
The right way is to use validate, which returns a JsResult. This forces you to handle the failure case explicitly.
val result = json.validate[Book]
result match {
case JsSuccess(book, _) => println(s"Got the book: ${book.title}")
case JsError(errors) => println(s"JSON was invalid: $errors")
}
Customizing the JSON keys
In the real world, you rarely get to dictate the JSON format. You'll often encounter APIs that use snake_case while your Scala code uses camelCase. If the API sends book_title instead of title, Json.format will fail because the names don't match.
To fix this, we stop using the macro and define the Reads and Writes manually. I'll do this by creating a custom Format using the (field) reads` notation.
implicit val customBookFormat: Format[Book] = new Format {
def reads(json: JsValue): JsResult[Book] = for {
title <- (json \ "book_title").as[String]
author <- (json \ "book_author").as[String]
price <- (json \ "book_price").as[Double]
tags <- (json \ "book_tags").as[List[String]]
} yield Book(title, author, price, tags)
def writes(book: Book): JsValue = Json.obj(
"book_title" → book.title,
"book_author" → book.author,
"book_price" → book.price,
"book_tags" → book.tags
)
}
Now we have a robust mapping that decouples our internal Scala naming conventions from the external API's requirements. It's more code, but it's where the actual reliability comes from.
📋 Practical Task
Implementing a Weighted Rating for the Book Inventory
You need to extend the Book inventory system to include a rating system. Follow these requirements:
- Update the
Bookcase class to include aratingfield of typeDouble. - Create a custom
Format[Book]that maps the Scala fieldratingto a JSON key calledaverage_rating. - Write a small test script that takes the following JSON string:
{"book_title": "Scala Mastery", "book_author": "Jane Doe", "book_price": 30.0, "book_tags": ["Advanced"], "average_rating": 4.8}. - Use
.validate[Book]to parse the string and print "Successfully parsed" if it works, or the specific errors if it fails.
There are no comments for now.