views:

128

answers:

2

I'm writing this question to maintain a register of design patterns associated with Scala, standards patterns or only from this language.

Associated questions:

Scala Catalog of functional Design Patterns

Thanks to all who contribute

+3  A: 

Let's start with the "Singleton pattern":

object SomeSingleton //That's it

I would additionally propose the "Using-functions-of-higher-order pattern". Instead of e. g. iterating through a collection by yourself you supply functions to the methods the classes provide.

In Scala you basically say what you intend to do:

//declare some example class
case class Person(name: String, age: Int) 

//create some example persons
val persons = List(Person("Joe", 42), Person("Jane", 30), Person("Alice", 14), Person("Bob", 12))

//"Are there any persons in this List, which are older than 18?"
persons.exists(_.age > 18)
// => Boolean = true

//"Is every person's name longer than 4 characters?"
persons.forall(_.name.length > 4)
// => Boolean = false

//"I need a List of only the adult persons!"
persons.filter(_.age >= 18)
// => List[Person] = List(Person(Joe,42), Person(Jane,30))

//"Actually I need both, a list with the adults and a list of the minors!"
persons.partition(_.age >= 18)
// => (List[Person], List[Person]) = (List(Person(Joe,42), Person(Jane,30)),List(Person(Alice,14), Person(Bob,12)))

//"A List with the names, please!"
persons.map(_.name)
// => List[String] = List(Joe, Jane, Alice, Bob)    

//"I would like to know how old all persons are all together!"
persons.foldLeft(0)(_ + _.age)
// => Int = 98

Doing this in Java would have meant touching the elements of a collection yourself and mix your application logic with flow control code.

More information about the Collection classes.


This nice EPFL paper about Deprecating the Observer Pattern might be of interest, too.


Typeclasses are one approach to structure common features of classes where inheritance doesn't really fit.

soc
It's sad that the "level" or common programming language is such that these ... constructs ... must be brought out and called "design patterns" (as if they should warrant any additional burden :-)
pst
"Using-functions-of-higher-order pattern" is GoF's Strategy
Synesso
+4  A: 

A list like this has been collated already. See http://scala.sygneca.com/patterns/start

Synesso