This page dicusses the Scala language and converting java to scala.
Much of the scala syntax is similar to java and it can use the java class library so in theory it should be relativly easy to convert between java and scala. However it is best to write programs directly in scala using a functional style rather than doing a line by line translation.
Sometimes though we need to get things working quickly and then improve the style quickly so here are some notes that I have made about how to convert:
Import and Class Declaration
Java | Scala | |
---|---|---|
import | import javax.swing.* | import javax.swing._ |
class declaration | public class AttributeList {... | class AttributeList {... |
primary constructor | class myClass{ myClass(int par) {...} } |
class myClass(par: Int){ {...} } |
secondary constructor | classname(...) | this(...) |
Object and Method declarations
Java | Scala | |
---|---|---|
private Hashtable list; | var list: Hashtable | |
public AttributeList() {... | def AttributeList(): Unit={... | |
method declaration | private int size() {... | def size(): Int={... |
array declaration | char[] arr; | var arr: Array[Char] |
class person extends Object implements property{...} |
class person() extends Object with property{...} |
|
super(msg) | super.Exception(msg) | |
x instanceof String | x.instanceOf[String] | |
procedure() throws Exception { |
Control Structures
Java | Scala | |
---|---|---|
return (String) value; | return value.asInstanceOf[String] | |
array declaration | char[] arr; | var arr: Array[Char] |
two dimensional array | othersign boolean[][]=new boolean(2)(2) | var otherSign:Array[Array[Boolean]] = new Array[Array[Boolean]](2,2); |
for loop | for(i=0;i<len;i++){...} | var i:Int=0; |
try catch |
try{...} catch(Exception e){...} |
try{...} catch{case e: Exception =>{...}} |
class person extends Object implements property{...} |
class person() extends Object with property{...} |
|
super(msg) | super.Exception(msg) | |
x instanceof String | x.instanceOf[String] | |
procedure() throws Exception { | ||
for | for (i <- 0 until args.length) var greeting = "" for (i <- 0 until args.length) { greeting += (args(i) + " ") } |
|
foreach | for (String arg : args) for (polynomialTerm sn:terms){ sn.multiplyBy(m); } |
args.foreach { arg => greeting += (arg + " ") } terms.foreach((sn:polynomialTerm) => {sn.multiplyBy(m)}) |
switch | switch (t) { case product: if (tableGeometric ==null) tableGeometric = new table(dimension,signMap,zeroMap,subAlgebra,elementLabels); return tableGeometric; case inner: if (tableInner ==null) tableInner = new table(dimension,signMap,zeroMap,subAlgebra,elementLabels); return tableInner; case outer: if (tableOuter ==null) tableOuter = new table(dimension,signMap,zeroMap,subAlgebra,elementLabels); return tableOuter; } |
object t {
def main(args: Array[String]) : unit = {
args.length match { case 1 => Console.println("1 argument"); case 2 => Console.println("2 arguments"); case _ => Console.println("more than 2!"); } } } |
Feature | Java | Scala |
---|---|---|
Static Typing | Yes | Yes |
Object Oriented programming | Yes | Yes |
Functional programming | No | Yes |
Variable declaration |
|
|
Constant declaration |
|
|
Class declaration |
|
|
Methods |
|
|
Constructors | Method(s) with same name as class name with no return type.
|
Constructor parameters are specified in class declaration itself.
Example:
You can have "secondary constructors" as well. Example:
|
Operator overloading | No. Except that string concatenation can be done using "+" - which gets transformed as "concat" calls. | Yes. Just use operator as method name. Example:
Also, any single parameter method can be used as an infix operator.
Example:
See also: Scala operators |
Static fields and methods |
|
|
Singletons | No language support. You can simulate something like this:
|
Singleton "objects" are in effect "modules" in Scala. Also, every Java class
is viewed like any other Scala class without static methods and fields
and a singleton object [whose name is same as Java class name] that contains
only the static methods and fields of Java class as it's (non-static) members.
This allows accesing static methods of Java classes but at the same time
not having static members in Scala. |
Inheritance |
|
See also: Scala subclassing.
But, this reference needs update. Now, Java (since JDK 5.0) supports
covariant return types. |
Calling super class constructor |
|
You call super class constructor in class declaration itself.
|
Method Overriding |
@Override is optional - but helps with detecting errors (you may be thinking
you are overriding - but in fact you may actually be overloading a super
class method). |
The keyword "override" is mandatory for non-abstract method overrides. |
Abstract classes and methods |
|
No "abstract" keyword for methods. Only for classes. |
Root of all reference types | java.lang.Object | scala.AnyRef - which is same as java.lang.Object in JVM implementation of Scala |
Uniform object orientation? (i.e., is everything object?) | No. There are primitive types and reference types. But with autoboxing/unboxing, you don't need to explicitly convert b/w primitive types and corresponding box types. | Yes. "int" is an alias to "scala.Int" and so on. A bit explanation of
type hierarchy. scala.Any is supertype of all types. scala.AnyVal is super
type of value types (such as "int" etc.). scala.AnyRef is super type of
all "reference" types. But, method calls etc. work on value types as well.
Examples:
|
interfaces |
|
Use traits. Traits are like interface but can have method bodies (i.e., not just
method declarations). See also: multiple inheritance.
|
Multiple inheritance | No. Only multiple interfaces may be implemented. Only single class may be extended. | Multiple classes can not be extended. Multiple traits can be.
And traits can have code -- not just declarations.
See also: Scala mixins, mixins paper, traits paper. |
Inner classes |
|
Unlike Java where such inner classes are members of the enclosing class, in Scala inner classes are bound to the outer object. With the above classes, in Java you can write
In other words, order for "Freakonomics" book can not be treated
as instance of order for "Let us kill Gandhi"! If you really want to refer
to inner class type as in Java, you can use the following:
See also: Scala inner classes. |
Class literals [section 15.8.2 of JLS]. |
|
See also: Scala classOf. |
Dynamic type check |
|
|
Dynamic type cast |
|
|
Generics |
|
See also: Scala generics. |
Generic methods |
|
See also: Scala polymorphic methods. |
Bounded type parameter |
|
|
Wildcards |
See also: Wildcards paper |
In Java, variance annotations are specified by "clients" [a.k.a use-site]. In
Scala, if you want Foo[A] to be subtype of Foo[B] whenever A is subtype of B,
you have to declare Foo as
Example: In Scala, Lists are immutable and List has covariant annotation. So, List[B] is subtype of List[A] whenever B is subtype of A. See also: Scala variances |
Arrays |
|
Array is a generic type in Scala (much like "Vector", "List" etc.
in Java are). Note: Arrays do not follow the covariant subtype rule.
i.e., Array[Graduate] is not a subtype of Array[Person] even if Graduate is subtype
of Person - this is unlike Java language in which Graduate[] |
Array element access, update |
|
|
Varargs |
With '...' after type of last parameter, your method becomes variadic. The type
of "values" in above example is int[] . In general, the
type would be T[] , if the last param type was T... . |
With '*' for the last parameter, your method becomes variadic. The type
of "values" in above example is Seq[int] . In general, the
type would be Seq[T] , if the last param type was T* . |
Type inference | Only for generic methods ( possible future improvements?) | Supported everywhere possible. Examples:
See also: Scala type inference. |
Functions, anonymous functions and closures | Not yet. May be in future?. | Yes. Can define functions, anonymous functions and closures
anywhere -- except in top-level scope (compilation unit level).
See also: Scala views. |
List support | Use java.util.List and classes implementing it. |
Lists in Scala are immutable. There are methods
on List class - like map, filter etc. that accept
closure arguments. Examples:
scala.List has covariant type parameter [note: Lists are immutable].
So, List[Graduate]
|