parse

Scala: How to parse a number from a String alvin July 10, 2017 - 1:25pm

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.1, “Parsing a Number from a String.”

Problem

You want to convert a String to one of Scala’s numeric types (Byte, Double, Int, Float, Long, Short).

How to parse JSON data into an array of Scala objects

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 15.4, “How to parse JSON data into an array of Scala objects.”

Problem

You have a JSON string that represents an array of objects, and you need to deserialize it into objects you can use in your Scala application.

How to process a CSV file in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.5, “How to process a CSV file in Scala.”

Problem

You want to process the lines in a CSV file, either handling one line at a time or storing them in a two-dimensional array.

Solution

Combine Recipe 12.1, “How to Open and Read a Text File” with Recipe 1.3, “Splitting Strings”. Given a simple CSV file like this named finance.csv:

Scala: How to parse a number from a String alvin May 30, 2015 - 6:34pm

Scala FAQ: How do I parse a number (Int, Long, Float, etc.) from a String in Scala?

Solution

Use the to* methods that are available on a String (courtesy of the Scala StringLike trait):

How to process multiple Option values in a Scala ‘for’ loop

My last edits to the Scala Cookbook were in June, 2013, and after all this time there aren’t many things I wish I had added to the Cookbook. Yesterday I ran into one thing that I don’t think I included in the Cookbook: How to process multiple Option values in a Scala for loop (for comprehension). Here’s a quick look at how to do this.

For the impatient

For those who just want to see a for comprehension that processes multiple input Option values, here you go:

An Android Java, JSON, and Twitter REST API example

I don't get to parse too much JSON code with Java because the biggest JSON source I work with is Twitter, and I always use the Twitter4J project to interact with their web services. But a few days ago while working on an Android project, I just wanted to access their "Twitter Trends" REST service, and I used Java and the json.org Java library that comes with Android to parse the Twitter Trends JSON feed like this: