generic

A Scala ‘foldLeft’ function written using recursion alvin January 20, 2018 - 4:25pm

As a short note, here’s some Scala source code that shows how to write a foldLeft function using recursion:

Scala: How to define a generic method parameter that must extend a base type alvin August 9, 2017 - 7:09pm

In today’s installation of “how to have fun with Scala,” if you want to define a method that takes a parameter that has a generic type, and want to further declare that the parameter must extend some base type, use this syntax:

def getName[A <: RequiredBaseType](a: A) = ???

That example says, “The parameter a has the generic type A, and A must be a subtype of RequiredBaseType.”

Two steps to deriving a generic algorithm alvin June 16, 2017 - 11:00am

“Two steps are required to write a good piece of code. The first step is to get the algorithm right. The second step is to figure out which sorts of things (types) it works for.”

From the “Deriving a Generic Algorithm” chapter in the book, From Mathematics to Generic Programming.

How to write a Scala method that takes a simple generic type

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 19.2, “How to write a Scala method that takes a simple generic type.”

Problem

You’re not concerned about type variance, and want to create a Scala method (or function) that takes a generic type, such as a method that accepts a Seq[A] parameter.

How to create Scala classes that use generic types (cookbook examples)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 19.1, “How to create Scala classes that use generic types (cookbook examples).”

Problem

You want to create a Scala class (and associated methods) that uses a generic type.

Android: Generic methods to write/save Android preferences data

I was working with Android Preferences recently, and after writing a few “save my preference” methods, I decided to take a few minutes to organize my code and put all of those Preference methods in a PreferenceUtils class. I made the methods static, and following functional programming principles, I made their output depend only on their input, so they require you to pass in a Context reference, along with your preference key and value.