Doing the more common things in Scala and Go

Page content

With Scala and Go becoming my more used language these days, I am trying to compare and contrast some of the language features and how we do some of the common things on both. I will use the most popular libraries in scala/go to demo these features.

Variable declaration

Making Http Calls

JSON parsing

Scala: Circe is good lib for doing Json Parsing in Scala

// build.sbt
val circeVersion = "0.9.3"

libraryDependencies ++= Seq(
  "io.circe" %% "circe-core",
  "io.circe" %% "circe-generic",
  "io.circe" %% "circe-parser"
).map(_ % circeVersion)

// Customer.scala
import io.circe._, io.circe.generic.auto._, io.circe.parser._
case class Customer(id: String, name: String, address: Option[String])
object MyApp extends App {
    val customerJson = s"""{
        "id": "1",
        "name": "john",
        "address": "422 smith st"
    }"""
    val customer = decode[Customer](customerJson)
    println(customer)
}

Go: Go comes with its own Json Encoder/Decoder

// Customer.go
import (
    "encoding/json"
    "fmt"
)
type Customer struct {
    id string `json:"id"`
    name string `json:"name"`
    address string `json:"address", omitempty`
}

function Main() {
    var customerJson = []byte {
        "id": "1",
        "name": "john",
        "address": "422 smith st"
    }
    var customer Customer
    json.Unmarshal(customerJson, &customer)
    fmt.Println(customer)
}