## Monday, February 22, 2010

### Methods of PartialFunction object

This topic looks at the functionality provide in the object PartialFunction.

This example uses Scala 2.8 which I believe is required.

Only two methods are focused on. PartialFunction.cond and PartialFunction.condOpt.
As per request the signature for said methods are:
`def cond[T](x: T)(pf: PartialFunction[T, Boolean]): Booleandef condOpt[T, U](x: T)(pf: PartialFunction[T, U]): Option[U]`
Now for some examples:
`scala>  import PartialFunction._import PartialFunction._scala> def strangeConditional(other: Any): Boolean = cond(other) {     |  case x: String if x == "abc" || x == "def"  => true     |  case x: Int => true     | }strangeConditional: (other: Any)Booleanscala> strangeConditional("abc")res0: Boolean = truescala> strangeConditional("hello")res1: Boolean = falsescala> strangeConditional(3)      res2: Boolean = truescala> def onlyInt(v: Any): Option[Int] = condOpt(v) { case x: Int => x }onlyInt: (v: Any)Option[Int]scala> onlyInt("hi")res3: Option[Int] = Nonescala> onlyInt(3)res4: Option[Int] = Some(3)scala> import util.control.Exception.catchingimport util.control.Exception.catchingscala> object IntNum {      |  val number = catching(classOf[NumberFormatException])     |  def unapply(x : Any) = condOpt(x) {     |      case x : Int => x     |      case y : String if number.opt(y.toInt).isDefined => y.toInt     |    }     | }defined module IntNumscala> 1 match { case IntNum(x) => println(x+" i win!")}   1 i win!scala> 3 match { case IntNum(x) => println(x+" i win!")}3 i win!`

## Friday, February 19, 2010

### =>? type alias for PartialFunction

A big thanks to Ben Jackman for this tip.

His tip cleans up the examples in post Chaining Partial Functions with orElse
The secret is to define the type alias `type =>?[-A, +B] = PartialFunction[A, B]`. This alias may be added to Predef in the future but until it is you can add it yourself.
`scala> type =>?[-A, +B] = PartialFunction[A, B]defined type alias \$eq\$greater\$qmarkscala> val i : (Any =>? Unit) = {case x:Int => println("int found")}i: =>?[Any,Unit] = < function1>scala> val j : (Any =>? Unit) = {case x:Double => println("Double found")}j: =>?[Any,Unit] = < function1>scala> val * : (Any =>? Unit) = {case x=> println("Something else found")}*: =>?[Any,Unit] = < function1>scala> (i orElse j orElse *)(1)int foundscala> (i orElse j orElse *)(1.0)Double foundscala> (i orElse j orElse *)(true)Something else foundscala> def =>?[A, B](id : A =>? B) = id\$eq\$greater\$qmark: [A,B](id: =>?[A,B])=>?[A,B]scala> ( =>?[Any, Unit]{case s : String => println("String found")} orElse j orElse *)("hello")String found`

## Thursday, February 18, 2010

### Chaining Partial Functions with orElse

PartialFunctions are extremely valuable Scala constructs that are used in many APIs. Commonly you will encounter the pattern:
`obj match {case "Val" => // do somethingcase _ => // handle all other cases}`
It is intuitive and obvious how to share the code of the right hand side if the case statement by factoring that code out to a method. But would it not be useful to be able to factor out an entire case statement (PartialFunction) and later chain them together as needed?

This is indeed possible and very easy to do:
`/*We need to declare Partial Functions so to add brevity I am adding this alias*/scala> import scala.{PartialFunction => PF}import scala.{PartialFunction=>PF}/*You have to explicitly declare the type because the type inferencer cannot know what type of PartialFunction to create A PartialFunction is Strictly type so some functions can only be used on Ints for example*/scala> val i : PF[Any, Unit] = {case x:Int => println("int found")}i: PartialFunction[Any,Unit] = < function1>scala> val j : PF[Any, Unit] =  {case x:Double => println("Double found")}j: PartialFunction[Any,Unit] = < function1>scala> val * : PF[Any, Unit] =  {case x=> println("Something else found")}*: PartialFunction[Any,Unit] = < function1>/*one might think that you can do:1 match (i orElse j orElse *)but in fact (i orElse j orElse *) forms a PartialFunction not a pattern so cannot be used with match.  Instead it must be used as a function*/scala> (i orElse j orElse *)(1)int foundscala> (i orElse j orElse *)(1.0)Double foundscala> (i orElse j orElse *)(true)Something else found/*for specific cases it is possible to chain the an anonymous partial function with the common functionThis is not so nice so it is probably best to declare a val instead of inline like this*/scala> (({case s:String => println("String found")}:PF[Any,Unit]) orElse j orElse *)("hello")String found`
For another example of chaining PartialFunctions the Akka tutorial has a good example in the ChatServer trait: http://jonasboner.com/2010/01/04/introducing-akka.html

## Tuesday, February 16, 2010

### And Case Statements

Recently I encountered a good question on Stack Overflow about matching.
http://stackoverflow.com/questions/2261358/pattern-matching-with-conjunctions-patterna-and-patternb.

As mentioned in an earlier post Matching with Or case expressions suppose 'or' expression combination using the '|' character. However 'and' combinations are not possible.

One solution is to build an && extractor object as follows:
`scala> case object && {  def unapply[A](a: A) = Some((a, a))}defined module \$amp\$ampscala> object StartsWith {  def unapply(s: String) = s.headOption}defined module StartsWithscala> object EndsWith {  def unapply(s: String) = s.reverse.headOption}defined module EndsWithscala> "foo" match {  case StartsWith('f') && EndsWith('o') => println("f*o") }f*o`
Note: this is a scala 2.7 solution Scala 2.8 can be used to improve the EndsWith extractor by using the method lastOption instead of s.reverse.headOption.

## Monday, February 15, 2010

### Self Annotation vs inheritance

At first glance the "sself annotation" declaration seems similar to extending another class. (For a look at self annotations read the topic: Self Type.) They are completely different but the comparison is understandable since both of them provide access to the functionality of referenced class.

For example both of the following compile:
`class Base {  def magic = "bibbity bobbity boo!!"}trait Extender extends Base {  def myMethod = "I can "+magic}trait SelfTyper {  self : Base =>     def myMethod = "I can "+magic}`
But the two are completely different. Extender can be mixed in with any class and adds both the "magic" and "myMethod" to the class it is mixed with. SelfType can only be mixed in with a class that extends Base and SelfTyper only adds the method "myMethod" NOT "magic".

Why is the "self annotations" useful? Because it allows several provides a way of declaring dependencies. One can think of the self annotation declaration as the phrase "I am useable with" or "I require a".

The following example demonstrates one possible reason to use self annotations instead of extend.

Note: These examples can be pasted into the REPL but I have shown that here because it would make the examples too long.
`import java.io._import java.util.{Properties => JProps}trait Properties {  def apply(key:String) : String}trait XmlProperties extends Properties {  import scala.xml._    def xml(key:String) = Elem(null,key,Null,TopScope, Text(apply(key)))}trait JSonProperties extends Properties {  def json(key:String) : String = "%s : %s".format(key, apply(key))}trait StreamProperties {  self : Properties =>     protected def source : InputStream    private val props = new JProps()  props.load(source)    def apply(key:String) = props.get(key).asInstanceOf[String]}trait MapProperties {  self : Properties =>    protected def source : Map[String,String]  def apply(key:String) = source.apply(key)}val sampleMap = Map("1" -> "one", "2" -> "two", "3" -> "three")val sampleData = """1=one                    2=two                    3=three"""val sXml = new XmlProperties() with StreamProperties{              def source = new ByteArrayInputStream(sampleData.getBytes)           }val mXml = new XmlProperties() with MapProperties{              def source = sampleMap           }val sJSon = new JSonProperties() with StreamProperties{              def source = new ByteArrayInputStream(sampleData.getBytes)            }val mJSon = new JSonProperties() with MapProperties{              def source = sampleMap            }sXml.xml("1")mXml.xml("2")sJSon.json("1")mJSon.json("2")`
The justification for using self annotations here is flexibility. A couple other solutions would be
1. Use subclassing - this is poor solution because there would be an explosion of classes. Instead of having 5 traits you would need 7 traits. Properties, XmlProperties, JSonProperties, XmlStreamProperties, XmlMapProperties, JsonStreamProperties and JsonMapProperties. And if you later wanted to add a new type of properties or a new source like reading from a database then you need 2 new subclasses.
2. Composition - Another strategy is to use construct the XmlProperties with a strategy that reads from the source. This is essentially the same mechanism except that you need to build and maintain the the dependencies. It also makes layering more difficult. For example:
`trait IterableXmlProperties {                                                self : MapProperties with XmlProperties =>     def xmlIterable = source.keySet map {xml _}  }    new XmlProperties with MapProperties with IterableXmlProperties {def source = sampleMap}`

The next question that comes to mind is why use extends then if self annotation is so flexible? My answer (and I welcome discussion on this point) has three points.
1. The first is of semantics and modeling. When designing a model it is often more logical to use inheritance because of the semantics that comes with inheriting from another object.
2. Another argument is pragmatism.
Imagine the collections library where there is no inheritance. If you wanted a map with Iterable functionality you would have to always declare Traversable with Iterable with Map (and this is greatly simplified). That declaration would have to be used for virtually all methods that require both the Iterable and Map functionality. To say that is impractical is an understatement. Also the semantics of Map is changed from what it is now. The trait Map currently includes the concept of Iterable.
3. The last point is sealed traits/classes. When a trait is "sealed" all of its subclasses are declared within the same file and that makes the set of subclasses finite which allows certain compiler checks. This (as far as I know) cannot be done with self annotations.

## Friday, February 12, 2010

### Specs and Fixtures/Contexts

This topic revisits the Specs BDD testing library. It is a continuation of the previous post Specs BDD Testing Framework.

This topic will look at how to setup fixtures in Specs. This is only a sample to give a feeling of Specs a much more complete guide is available on the Specs website.
`jeichar: git-src\$ scala -classpath ~/.m2/repository/org/scala-tools/testing/specs/1.6.1/specs-1.6.1.jarscala> import org.specs._import org.specs._/*This example demonstrates before and after actions similar to what is found in XUnit.*/scala> object mySpec extends Specification {                | "my system" should {     | doFirst{println("before")}  // ran once     |      | doBefore{println("before")} // ran for each test     | doAfter{println("after")} // ran for each test     |      | "test spec 1" in { println("test1"); 1 must_== 1}     | "test spec 2" in { println("test2"); 1 must_== 2}     |      | doLast{println("last")} // ran once     | }}defined module mySpecscala> mySpec.main(Array())                             Specification "mySpec"  my system shouldbeforebeforetest1after  + test spec 1beforetest2afterlast  x test spec 2    '1' is not equal to '2' (< console>:14)Total for specification "mySpec":Finished in 0 second, 307 ms2 examples, 2 expectations, 1 failure, 0 error`
Example using Contexts there many more examples at: Shared contexts
`scala> import org.specs._import org.specs._/*This specification uses contexts instead of before and after actions.My personal preference is to use contexts because they are more flexible and can have names associated with them.  In addition contexts can be shared between specifications and multiple contexts can be used within a single specification.  This example is kept very simple for demonstration purposes*/scala> object StackSpecification extends Specification {     |   var list : List[Int] = _     |   val empty = beforeContext(list = Nil)       |   val nonEmpty = beforeContext(list = List(1,2,3))     |        |   "A full stack" definedAs nonEmpty should {      |     "size of 3" in {     |       list must haveSize (3)     |     }     |   }     |   "A stack" when empty should {      |     "is empty" in {     |       list must beEmpty     |     }     |   }     | }defined module StackSpecificationscala> StackSpecification.main(Array())Specification "StackSpecification"  A full stack should  + size of 3  Total for SUS "A full stack":  Finished in 0 second, 42 ms  1 example, 1 expectation, 0 failure, 0 error  A stack should  + is empty  Total for SUS "A stack":  Finished in 0 second, 4 ms  1 example, 1 expectation, 0 failure, 0 errorTotal for specification "StackSpecification":Finished in 0 second, 85 ms2 examples, 2 expectations, 0 failure, 0 error`

## Thursday, February 11, 2010

### Selection with Implicit Methods

This tip is a cool tip based on Daniel's Use Implicits to Select Types post. That post goes into more detail.

The idea is that depending on a given parameter of type T a particular type of object is required. There are several ways to do this. One would be to use matching to match the type T and create the correct object. Most likely the biggest draw back to matching is caused by type erasure. The following solution gets around that issue.

Two very interesting points.
1. Implicit methods do not require parameters. They can be selected based only on type parameters
2. Implicit methods are not subject to type erasure
`// the base class we needscala> abstract class X[T] { def id :Unit }defined class X/*One of the types we need created.  It is the catch all case*/scala> implicit def a[T] =new X[T] { def id =println("generic") }a: [T]X[T]/*A specific subclass for integers*/scala> implicit def b =new X[Int] { def id =println("Int") }b: X[Int]/*One simple usage.  The most specific implicit will be used to create the object to be passed to g.  */scala> def f[T](a :T)(implicit g :X[T]) = g.idf: [T](a: T)(implicit g: X[T])Unitscala> f(5)Intscala> f('c')generic/*This example demonstrates how erasure is not an issue because the selection of the implicit is done at compile time so the correct type is selected.  If a match was used instead then a more complicated solution would be required*/scala> def g[T](l:List[T])(implicit i:X[T]) = i.id          g: [T](l: List[T])(implicit i: X[T])Unitscala> g(List(1,2,3))Intscala> g(List("a",2,3))generic`

## Tuesday, February 9, 2010

### Structural Types: Multiple Methods and Type Aliasing

There are two more aspects related to structural typing that are useful to look at. Structural types with multiple methods and type aliases.

For background on this topic also look at:
Structural Types are not limited to defining a single method. In that regard they are very similar to interfaces without the binary incompatibility issues. However do not be fooled into thinking they are the same thing. For one reason reflection is used so performance can be an issue in certain cases and also interfaces/traits have semantics that structural types do not.
`/*Defining a types that has both a length and charAt method.  Just a warning.  If you leave off the () after length this will not work.  This is not a bug.  Martin kindly left a comment on why it is not.*/scala> def foreach(t : {def length():Int; def charAt(i:Int):Char}, f : Char => Unit) = {     | 0 until t.length foreach {i => f(t.charAt(i))}       | }foreach: (t: AnyRef{def length(): Int; def charAt(i: Int): Char},f: (Char) => Unit)Unit// A string matches the structural typescala> foreach ("hello", println _)hello`
Pretty unexpected I would say. A feature of Scala which complements Structural types are type aliases. They are useful in many situations and one is with use with Structural Types:
`/*With type aliasing you can assign a structural type a name*/scala> type IChar = {def length():Int     |               def charAt(i:Int):Char}defined type alias ICharscala> def print( t : IChar) = 0 until t.length() foreach {i => println(t.charAt(i))}print: (t: IChar)Unitscala> print("gurk")gurk`

## Monday, February 8, 2010

### Dynamic calls using Structural Types

Using reflection can be a real pain in Java since the API is a Java API and consists of many gets and searches through collections not to mention so many exceptions that need to be handled. In Scala there is a wonderful way to clean up a reflective call down to a single line (assuming you don't want to worry about handling exceptions.) Here structural typing can really be a pleasure.
`// I am assigning a string to an Any referencescala> val s:Any = "hello :D"s: Any = hello :D// Any does not have a length methodscala> s.length< console>:6: error: value length is not a member of Any       s.length         ^/*But I can cast it to a structural type with a length method*/scala> s.asInstanceOf[{def length:Int}].lengthres2: Int = 8`
There are restrictions to this. For example implicits will not work:
`/*The method r is part of StringLike (or RichString in Scala 2.7) and there is an implicit conversion from String to RichString/StringLike.The structural type does not try to apply the implicits because implicits are acompile time artifact and that information is not kept at run time.  Perhaps thiswill be added in the future but it is not present now.*/scala> s.asInstanceOf[{def r:util.matching.Regex}].rjava.lang.NoSuchMethodException: java.lang.String.r()`
More examples:
`scala> val s:Any = "hello :D"s: Any = hello :Dscala> s.asInstanceOf[{def charAt(x:Int):Char}].charAt(2)res9: Char = l/*This is interesting.  The actual method returns Char, but Char iscompatible with Any so this cast works.*/scala> s.asInstanceOf[{def charAt(x:Int):Any}].charAt(2) res10: Any = l// Now lets test to see if that lenience is available for parameters:scala> class X defined class Xscala> class Y extends Xdefined class Yscala> class T {     | def x(x:X):Int = 1     | }defined class Tscala> val a:Any = new T()a: Any = T@687c3b99scala> a.asInstanceOf[{def x(x:X):Any}].x(new Y())res11: Any = 1/*Ok so return values can be subclasses but not params*/scala> a.asInstanceOf[{def x(x:Y):Any}].x(new Y())java.lang.NoSuchMethodException: T.x(Y) at java.lang.Class.getMethod(Class.ja`
Use with care :-D

## Friday, February 5, 2010

### Introducing Structural Types

Structural types allows one to declare types based on the methods the type has. For example you could define a method that takes a class containing a close method. This is fairy analogous to duck-typing in dynamic languages. Except that it is statically enforced.

The main example used here was from a comment on the Code Monkeyism Blog. The commenter further explains that this example is in fact from Beginning Scala chapter 4 (which I would like to read but have not yet had the time.)
`/*A can be any object that has a close method.  This is statically typed which makes some restrictions which are explained later*/scala> def using[A <: {def close(): Unit}, B](param: A)(f: A => B): B =      | try {     |     f(param)     |   } finally {     |     try {     |        param.close()     |     } catch { case _ => () }     |   }using: [A <: AnyRef{def close(): Unit},B](param: => A)(f: (A) => B)Bscala> using(new java.io.ByteArrayInputStream("hello world".getBytes)){ in =>      | io.Source.fromInputStream(in) foreach (print)                               | }hello worldscala> using(new java.io.ByteArrayInputStream("hello world".getBytes)){ in =>      | io.Source.fromInputStream(in) mkString ""                                   | }res8: String = hello world`
That is extremely powerful and the consequences will be visited more in the future. But because structural typing is statically enforced it is not quite as flexible as dynamic language's version of duck typing. For example you cannot do:
`scala> val i:Any = new java.io.ByteArrayInputStream("hello world".getBytes)i: Any = java.io.ByteArrayInputStream@145a25f3/*This does not work because 'i' is defined as type Any.  Not a type that is closeable.  Casting can be used to get around this issue.  I will address that in its own post*/scala> using(i){ in =>      | io.Source.fromInputStream(in) mkString ""     | }< console>:8: error: inferred type arguments [Any,B] do not conform to method using's type parameter bounds [A <: AnyRef{def close(): Unit},B]       using(i){ in =>`
An alternative to the first using example is to use call by name to construct the closeable. The reason one might want to do that is because it allows currying of the method:
`scala> def using[A <: {def close(): Unit}, B](param: =>A)(f: A => B): B =      | val closeable = param  // notice param is only referenced once     | try {     |     f(closeable)     |   } finally {     |     try {     |        closeable.close()     |     } catch { case _ => () }     |   }using: [A <: AnyRef{def close(): Unit},B](param: => A)(f: (A) => B)B/*if this was accessing a database a new connection would be made automatically each time this function was used*/scala> val usingTheWorld = using[BStream,Int](new java.io.ByteArrayInputStream("hello world".getBytes))_usingTheWorld: ((java.io.ByteArrayInputStream) => Int) => Int = < function1>scala> usingTheWorld { s => io.Source.fromInputStream(s).length}  res3: Int = 11scala> usingTheWorld { s => io.Source.fromInputStream(s).getLines().length}res5: Int = 0`

## Wednesday, February 3, 2010

### Regex ReplaceAllIn

Note: Updated on Feb 13th for the newer API on Scala 2.8 trunk. (This is life on the bleeding edge, thanks Daniel).

A couple new methods have just been added to Scala 2.8 Regex. You will need to download a version of Scala 2.8 more recent than Scala2.8-Beta1.

The methods are related to replacing text using a regular expression and to say they are useful is an understatement. Lets take a look:
`scala> val quote = """I don't like to commit myself about heaven and hell - you see, I have friends in both places.      | Mark Twain"""                                                                                                quote: java.lang.String = I don't like to commit myself about heaven and hell - you see, I have friends in both places. Mark Twainscala> val expr = "e".r    expr: scala.util.matching.Regex = e/* This first method is not new or is it interesting.  But the new methods are both relatedso lets start with the basic form of replaceAllIn*/scala> expr.replaceAllIn(quote, "**")res1: String = I don't lik** to commit mys**lf about h**av**n and h**ll - you s****, I hav** fri**nds in both plac**s. Mark Twain// this does the same thingscala> quote.replaceAll("e","**")res2: java.lang.String = I don't lik** to commit mys**lf about h**av**n and h**ll - you s****, I hav** fri**nds in both plac**s. Mark Twain/*Now things get interesting.  Using this form of replaceAllIn we can determine the replacement on a case by case basis.It provides the Match object as the parameter so you have complete access to all the matched groups, the location of the match etc...The method takes a Match => String function.  Very, very powerful.*/scala> expr.replaceAllIn(quote, s => if(util.Random.nextBoolean) "?" else "*")res5: String = I don't lik? to commit mys?lf about h?av?n and h?ll - you s*?, I hav? fri*nds in both plac*s. Mark Twain/*Another example using some of the matcher functionality*/scala> expr.replaceAllIn(quote, m => m.start.toString)                        res6: String = I don't lik11 to commit mys26lf about h37av40n and h48ll - you s5960, I hav68 fri73nds in both plac90s. Mark Twain/*Another crazy useful method is the replaceSomeIn.  It is similar to the replaceAllIn that takes a function except that the function in replaceSomeIn returns an Option.  If None then there is no replacement.  Otherwise a replacement is performed.  Very nice when dealing with complex regular expressions.In this example we are replacing all 'e's start are before the 50th character in the string with -*/scala> expr.replaceSomeIn(quote, m => if(m.start > 50) None else Some("-"))res3: String = I don't lik- to commit mys-lf about h-av-n and h-ll - you see, I have friends in both places.Mark Twain`

### Chaining Options with orElse

A simple but handy use for Option is to select the first valid option from a selection of possible choices. Sound vague? Well it is because it can be used in many different situations. The one presented here is: the program needs a directory that can be set by the user either as a system variable, and environment variable or the default value. The java code is a nightmare of if (xxx == null) statements. The Scala code is beautiful.
`scala> val propsTemplates = Option(System getProperty "MVN_CREATOR_TEMPLATES")propsTemplates: Option[java.lang.String] = Nonescala> val envTemplates = Option(System getenv "MVN_CREATOR_TEMPLATES")envTemplates: Option[java.lang.String] = Nonescala> val defaultHome = Some(System getProperty "user.home")defaultHome: Some[java.lang.String] = Some(/Users/jeichar)/* chain the different options together in order of priority and get the valueI am taking a small liberty here because I am assuming that user.home is always available*/scala> propsTemplates.orElse(envTemplates).orElse(defaultHome).getres0: java.lang.String = /Users/jeichar// alternative form:scala> propsTemplates orElse envTemplates orElse defaultHome getres1: java.lang.String = /Users/jeichar`

## Tuesday, February 2, 2010

### Blocks within for-comprehensions

In another example of uniformity it is possible to use blocks within a for-comprehension when creating a generator or making an assignment. The basic form of a for-comprehension is
`for {i <- generator      if guard     j = assignment } yield result`
The generator, guard, assignment and result are all expressions which means they can all be blocks or simple statements. Most commonly you will see them as simple statements:
`scala> for {i <- 1 to 10     |      if i % 2 == 0     |      j = i } yield jres50: scala.collection.immutable.IndexedSeq[Int] = IndexedSeq(2, 4, 6, 8, 10)`
But since they are expressions they can be more complex:
`scala> for {       |  i <- {      |     val start = nextInt(3)     |     val end = nextInt(10)+start     |     start to end     |  }     |  if {     |    val cut = nextInt(3)+1     |    i % cut == 0     |  }     |  j = {     |    val x = i+1     |    x / 2     |  }     |  }  yield {     |    // do a debug println     |    println(j)     |  j     |  }1123res53: scala.collection.immutable.IndexedSeq[Int] = IndexedSeq(1, 1, 2, 3)`

## Monday, February 1, 2010

### Temporary variables during object instantiation

In Java a common pattern with class constructors is to assign field values and often there are several intermediate values used for the calculation. If the code is ported to Scala the resulting class will have the intermediate values as fields, which take up space in the object. However the issue is easily worked around. Lets look at a couple examples.

Example 1: Assigning a single field
`//  Javaimport java.io.File/** No real logic behind class.  But for some reason it needs the path of a tmp directory in the working directory*/class OneAssignment {  final String field;  public OneAssignment() {    File file = new File("tmp");    if(!file.exists()) {      file.mkdirs();    }    field = file.getAbsolutePath();  }}`
In Scala the naive way to port this would be:
`//  Scalaimport java.io.Fileclass OneAssignment {  val file = new File("tmp")  if(!file.exists()) {    file.mkdirs()  }  val field = file.getAbsolutePath()}`
Problem is that it has an extra field "file" now. The correct way to port this would be as follows:
`//  Scalaimport java.io.Fileclass OneAssignment {/* notice that assignment is in a block so file is only visible within the block*/  val field = {    val file = new File("tmp")    if(!file.exists()) {      file.mkdirs()    }    file.getAbsolutePath()  }}`

Example 2: Assigning multiple fields
`//  Javaimport java.io.File/** Basically the same as last example but multiple fields are assignedNotice that 2 fields depend on the temporary file variable but count does not*/class MultipleAssignments {  final String tmp,mvn_repo;  find int count;  public OneAssignment() {    File file = new File("tmp");    if(!file.exists()) {      file.mkdirs();    }    tmp = file.getAbsolutePath();    count = file.listFiles.length;        File home = new File(System.getProperty("user.home"));    mvn_repo = new File(home, ".m2").getPath();  }}`
The Scala port:
`//  Scalaimport java.io.Fileclass MultipleAssignments {/*When multiple fields depend on the same temporary variables the fields can be assigned together from one block by returning a tuple and using Scala's matching to expand the tuple during assignment.  See previous topics on assignment for details */  val (tmp,count) = {    val file = new File("tmp");    if(!file.exists()) {      file.mkdirs();    }    val tmp = file.getAbsolutePath();    val count = file.listFiles.length;    (tmp, count)  }  val mvn_repo = {    val home = new File(System.getProperty("user.home"));    new File(home, ".m2").getPath();  }}`
In some ways the Scala port is cleaner in that it splits the constructor up and decouples the dependencies between fields.