java2scala #3: Variables and functions

December 29, 2009 – 12:17 am by Stefano MAESTRI
Share

In this third post of our java2scala series we will take a look to variables and functions definition and use.

As usual you can find the full maven/eclipse project on github.

Java class

package it.javalinux.samples.java.post3;
 
class VariablesAndFunctions {
 
	private final String inputString;
 
	public int fooIntVar = 11;
	public final String fooStringVal = "fooString";
	private double privateIntVar = 1.1;
	private final String privateStringVal = "fooString";
 
	public VariablesAndFunctions(String inputString) {
		//it could compile! and if you uncomment the line tests will fail
		//inputString = inputString + "hasBeenModified";
		this.inputString = inputString;
		//it doesent compile because you have already assigned the final property
		//this.inputString = inputString + "hasBeenModified";
		System.out.println("Created VariablesAndFunctions with inputString=" + inputString);
	}
 
	public VariablesAndFunctions() {
		this("defaultString");
	}
 
	public String getInputString() {
		return inputString;
	}
 
	public String getFooStringVal() {
		return fooStringVal;
	}
 
// i. You can't re-assign a final variable
//	public void setFooStringVal(String fooStringVal) {
//		this.fooStringVal = fooStringVal;
//	}
 
	public double getPrivateIntVar() {
		return privateIntVar;
	}
 
	public void setPrivateIntVar(double privateIntVar) {
		this.privateIntVar = privateIntVar;
	}
 
	public int getFooIntVar() {
		return fooIntVar;
	}
 
	public String getPrivateStringVal() {
		return privateStringVal;
	}
 
	public void setFooIntVar(int fooIntVar) {
		this.fooIntVar = fooIntVar;
	}
 
}

java Unit Test

package it.javalinux.samples.java.post3;
 
import org.junit.Test;
 
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
 
public class VariablesAndFunctionsTest {
 
    @Test
    public void testAccessToPublicVar() {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	instance.fooIntVar = 12;
    	assertTrue(instance.fooIntVar == 12);
    }
 
    @Test
    public void  testAccessToPublicVal()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	// It doesn't compile...you can't reassign a final property
    	//instance.fooStringVal = "anotherString"
    	assertTrue(instance.fooStringVal.equals("fooString") );
    	assertFalse(instance.fooStringVal == new String("fooString") );
    }
 
    @Test
    public void  testAccessToPrivateVar()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	instance.setPrivateIntVar(12);
    	assertTrue(instance.getPrivateIntVar() == 12);
    }
 
    @Test
    public void  testEmptyConstructor()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions();
    	assertTrue(instance.getInputString().equals("defaultString"));
    	assertFalse(instance.getInputString() == new String("defaultString") );
    }
 
    @Test
    public void  testConstructor()  {
    	VariablesAndFunctions instance = new VariablesAndFunctions("myString");
    	assertTrue(instance.getInputString().equals("myString"));
    	assertFalse(instance.getInputString() == new String("myString") );
    }
 
}

Scala class

package it.javalinux.samples.scala.post3
 
class VariablesAndFunctions(val inputString : String) {
 
    println("Created VariablesAndFunctions with inputString=" + inputString);
 
    // it doesnt compile
    // inputString = inputString + "hasBeenModified";
 
	def this() = this("defaultString")
 
	var fooIntVar : Int = 11
	val fooStringVal = "fooString"
	private var privateIntVar = 1.1
	private val privateStringVal = "fooString"
 
	def getPrivateVarIntVar() = privateIntVar
 
	def getPrivateStringVal() = privateStringVal
 
	def setPrivateVarIntVar(x : Int) {
	  privateIntVar = x
   	}
 
// It doesn't compile...you can't reassign val
//	def setPrivateStringVal(s : String) {
//	  privateStringVal = s;
//    }
 
}

Scala Unit Test

package it.javalinux.samples.scala.post3
 
import org.junit._
import Assert._
 
@Test
class VariablesAndFunctionsTest {
 
    @Test
    def testAccessToPublicVar() = {
    	val instance = new VariablesAndFunctions()
    	instance.fooIntVar = 12
    	assertTrue(instance.fooIntVar == 12)
    }
 
    @Test
    def testAccessToPublicVal() = {
    	val instance = new VariablesAndFunctions()
    	// It doesn't compile...you can't reassign val
 
    	//instance.fooStringVal = "anotherString"
    	assertTrue(instance.fooStringVal == new String("fooString") )
        assertFalse(instance.fooStringVal eq new String("fooString") )
    }
 
    @Test
    def testAccessToPrivateVar() = {
    	val instance = new VariablesAndFunctions()
    	instance.setPrivateVarIntVar(12)
    	assertTrue(instance.getPrivateVarIntVar == 12)
    }
 
    @Test
    def testEmptyConstructor() = {
    	val instance = new VariablesAndFunctions()
    	assertTrue(instance.inputString == new String("defaultString") )
        assertFalse(instance.inputString eq new String("defaultString") )
    }
 
    @Test
    def testConstructor() = {
    	val instance = new VariablesAndFunctions("myString")
    	assertTrue(instance.inputString == new String("myString") )
        assertFalse(instance.inputString eq new String("myString") )
    }
 
}

Ok, let me rapidly focus on some interesting things we can remark in previously pasted code (of course feel free to ask if I’ve missed to remark something that you’d like more explanations):

  • public is the default access modifier…conciseness one more time. Scala have 3 different access public (default), private and protected. While plublic and private are the same of java, protected is a bit more restrictive than java one: protected member can be accessed only by subclasses of the class in which they are defined; in java you can access protected memeber also by classes defined in the same package. In scala you can achieve this effect using scoped protection. I will explain that in further post: for the moment just take in mund that you can specify private[X] or protected[X] member meaning they are private or protected “up to” X where X could be an enclosing package or class.
  • scala has 2 different keyword to define mutable (var) and immutable variable. Immutable variable guarantee immutable state at compile time.
  • default constructor is defined implicitly in class definition:
    • every code put in the class except variables and methods definitions are considered part of the default constructor. In our case the println instruction for debug purpose.
    • every val defined into calss definition parenthesis act as parameter for the default constructor. It’s matter of facts that the inputString parameter is defined as val prevent any kind of modification. Of course you can do the same in java declaring the input parameter as final, but it’s quite less usual.
  • normally in scala public variables are accessed using variables names instead of odd getter and setter methods. BTW there is an annotation in scala to build getter and setter methods runtime. It is useful when you need java bean compatible objects written in scala.
  • a method or function is defined using keyword def
  • functions are methods that returns value. Normally defined using an = symbol after method name. Normally return keyword is not required and its use isn’t suggested, the last expression evaluated in the method is the returned one. Try to think functions as complex expression evaluation. Normally you don’t need to specify the type of returned value in method definition since scala will infer it for you. We will see type inference in one of next posts. For now just keep in mind that COMPILER will STATICALLY infer type for you.
  • The same STATIC inference of type is used to infer variable type when it isn’t specified. Try to play a little with my code to get idea about type inference of scala. It’s AMAZING.
  • methods without = symbol doesn’t return value. Formally they return an instance of Unit. Unit is the type of scala like void for java.
  • Don’t miss the different behaviour of == on object between scala and java. They are used in unit tests. Scala uses == to compare the content of objects, while it have eq operator to compare object references.

Ok that’s all for the moment, but as said feel free to play with my code and/or ask here any further explanations.

In next post of the series we will take a first look at scala’s type inference in some more detail. As said it’s absolutely AMAZING…stay tuned

 
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Slashdot
  • Technorati
  • YahooMyWeb
  • LinkedIn
  • StumbleUpon
  • TwitThis
  • Wikio

Post a Comment