About Adam Warski

Adam is one of the co-founders of SoftwareMill, a company specialising in delivering customised software solutions. He is also involved in open-source projects, as a founder, lead developer or contributor to: Hibernate Envers, a Hibernate core module, which provides entity versioning/auditing capabilities; ElasticMQ, an SQS-compatible messaging server written in Scala; Veripacks, a tool to specify and verify inter-package dependencies, and others.

Scala: Missing OO and FP bridge

Scala blends functional and object-oriented programming in many nice ways. You can use both FP an OO-like constructs whichever fits the current problem better. But there’s always room for improvement! Here’s one thing I think is missing (short version at the bottom).

FP side

It’s easy to convert a method to a function in Scala. For example, if you have a method:

def say(to: Person, what: String): String = { ... }

we can get the corresponding function using the underscore notation:

val sayFun: (Person, String) => String = say _

Moreover, Scala supports multiple parameter lists, which is sometimes also referred to as currying, and which makes partial application easier:

// Method with multiple parameter list
def connect(person1: Person)(person2: person): Connection = { ... }
// Function, created by partially applying the previous method
val createConnectionWithAdam: Person => Connection =
      connect(new Person('Adam')) _

OO side

One thing every class has is a constructor. But what is a constructor, really? You give values for the constructor’s arguments, and get a new instance of the class in return. So it’s really just a function!

class Person(name: String, age: Int) { ... }
// The 'signature' of new is (String, Int) => Person
val somebody = new Person('John', 34)

Link?

However, that’s where the combination of OO and FP fails in Scala: you can’t use the two features of methods (convert to function, currying) mentioned above with constructors. Both of these won’t work:

val makePerson: (String, Int) => Person = new Person _

class Person2(name: String)(age: Int) { ... }
val makeNewJack: Int => Person = new Person2('Jack') _

You can get around this using companion objects and apply (or any other factory method, apply just has a nicer notation afterwards):

object Person2 {
   def apply(name: String)(age: Int) = new Person2(name, age)

}
val makeNewJack: Int => Person = Person2('Jack') _

But that requires repeating the signature of the constructor in the companion object, and nobody likes code duplication, right? ;)

Use-case

Where can this be useful? For example in the classic factory example. Imagine you have a class which depends on some services, but also on some data available on runtime. Of course we use IoC so instances of the other services are provided to our class:

// This service depends on a concrete Person instance
class Service3(service1: Service1, service2: Service2)(person: Person) {
...
}
/ Note that the multiple parameter notation above als provides a nice
// separation of the parameters that should be 'injected' - services,
// and the data that can be variable.
// This service depends on Service1, and wants to create it having Person
// instances
class Service4(makeService3: Person => Service3) {
  // Usage:
  for (person <- persons) makeService3(person).doSomething()
}
class Main {
      // Bootstrap: (or - no-framework DI container ;) )
         val service1 = new Service1
         val service2 = new Service2
      // That's the part that is illegal in Scala
         val makeService3 = new Service3(service1, service2) _
         val service4 = new Service4(makeService1)
...
// Today we'd have to write: val makeService3 = (person: Person) => new Service3(//service1, service2, person)
}

That’s also connected to my post on DI and OO, and how current DI frameworks make it hard to define services which depend on data and services that we’d like to have multiple copies of.

Side note

When viewing constructors as methods/functions (which they are, really ;) ), I suppose the Ruby-like notation:

Person.new('John', 34)

would be better and adding support for _ and multiple parameter lists would be obvious.

Bottom line for TL;DR fans

Why not treat class constructors as every other method/function? Make this legal:

class Person(name: String, age: Int)
val makePerson = new Person _ // type: (String, Int) => Person

class Person2(name: String)(age: Int)
val makeNewJack = new Person2('Jack') _ // type: Int => Person

Reference: Missing OO and FP bridge in Scala from our JCG partner Adam Warski at the Blog of Adam Warski blog.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply


+ eight = 13



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books