1. Translating Java Classes to Scala Classes
Example 1:
inch Javapublic class book{}# Scala equivalent of a class Declarationclass book
Example 2:
# A Java class with a Construtorpublic class book{ int ISBN; Private final String title; Public book (int ISBN, String title) { = ISBN; = title; } int GETISBN () { return ISBN; } Public String GetTitle () { return title; } } # Scala equivalent class book (Val Isbn:int, Val title:string)
Example 3:
inch Javapublic class Nonfiction extends book{public nonfiction (String title) { Super (title); }} # Scala Equivalentclass Nonfiction (title:string) extends book (title)
Example 4:
inch Javapublic class book{ "Beginning Scala"; Public String GetTitle () { return title; } public void Settitle (String t) { = t; }} # Scala Equialentclass book{ "Beginning Scala"}
Example 5:
inch Javapublic class book{ int999; int GETISBN () { return ISBN; }} # Scala Equivalentclass book{ 999}
Translating Java Imports to Scala imports:
inch javaimport com.moda.classa;import com.modb.classb1;import com.modb.classb2;import Com.modC. *in// your can stack multiple importsfrom the same package in braces//
underscore in Scala imports are equivalent of * in Java imports
Example 6:
= = = = = title;}} # Refactoringclass Book (var isbn:int, var title:string)
If You create the book instance with a Construtor this takes a single "title" parameter, you'll get an error.
scala> val book = new book ("test")<console>: Constructor Book: (Isbn:int, title:string) book.unspecified value parameter title. = new book ("test")
We need an extra constructor for this case.
Scala> class Book (Var isbn:int, var title:string) { | def this (title:string) = This (0, title ) | }defined class Bookscala> Val book = new book ("test"= [email Protected]scala>0Scala>= Test
You can get and set "ISBN" and "title" because of the generated getters and setters that follow the Scala conversion.
2. JavaBeans Specification compliant Scala classes
To has Java-style getters and settersare to annotate the field with Scala.beans.BeanProperty. In this is the can interact with a Java CALSS or library that accepts only classes that conform to the JavaBean specific ation.
scala> Import scala.beans.BeanPropertyimport Scala.beans.BeanPropertyscala> class Book (@ Beanproperty var isbn:int, @BeanProperty var title:string) defined class book
After compiling Book.scala with scalac command and disassembling it with javap command:
public class Book {public int ISBN (); public void Isbn_$eq ( int int int GETISBN (); Public java.lang.String getTitle (); Public book ( int
The methods GETTITLE,SETTITLE,GETISBN,SETISBN has all been generated because of the @BeanProperty annotation. Note that use the @BeanProperty annotation in your fields, also making sure you declare each field as a var. If you declare your fields a type Val, the setter is methods won ' t be generated.
You can use @BeanProperty annotation on class constructor parameters, even on the ' fields ' in a Scala class.
3. Java Interfaces and Scala traits
A Java class can ' t extend a Scala trait that has implemented methods.
# A Regular Java Interface Declarationpublic interface book{public abstract Boolean isbestseller (); }
# Scala equivalent
Trait book{def Isbestseller:boolean}
Note in Scala, if there are no = assignment, then the methods denoted with a def keyword or the funct Ions denoted with a val keyword is abstract. That means if there's no definition provided with = and then it's automatically abstract.
# A concrete Java methodpublic String somemethod (int"voila" " Volia " int dothemath (int i) # Scala equivalentdef Dothemath (i:int): int
Example:you need to being able to the user an Add method from a Java application:
= A + b}# a Java applicationpublic class dothemath{public static void Main (string[] args) { = new DoT Hemath (); }}
Java class Dothemath cannot implement the trait computation because computation are not like a regular Java interface. To is able to use the implemented method add of a Scala trait computation from Java class Dothemath, you must wrap the TR AIT computation in a Scala class.
# Scala class that wraps the trait Computationclass Javainteroperablecomputation extends computation# accessing the ad D method of the Scala trait from Java classpublic class Dothemath extends javainteroperablecomputation{public static void Main (string[] args) { = new Dothemath (); D.add (3,1);} }
Note that wrap your Scala traits with implemented behavior in the Scala class for its Java callers.
4. Java static members and Scala objects
inch Scalapublic class book{ private static book book; Private book () {} public static synchronized book getinstance () { ifnull) { = new book (); } return book; }} # Scala equivalent, object can extend interfaces and traitsobject book{}
the companion object enables storing of static methods and from this, you has full access to the class's members, in cluding private ones. Scala Alows declare both an object and a class of the same name, placing the static members in the object and the I Nstancemembers in the class.
# Java class with instance and static Methodspublic class book{public String getcategory () { " C4>non-fiction"; } public static book Createbook () { return to new book (); } } # Scala Equivalentclass book{ "non-fiction"}Object book{ = new book ()}
5. Handling Exceptions
# A Scala method that throws an Exceotionclass someclass{ def ascalamethod{throw new Exception ("
exception
"
)}}# calling a Scala method from a Java classpublc static void Main (string[] args) { =
new SomeClass (); S.ascalamethod ();} # The uncaught exception causes the Java method to Fail[error] (run-main) java.lang.exception:exception!
java.lang.Exception:Exception! At
Someclass.ascalamethod
For the Java callers of your Scala methods, add the @throws annotation to your Scala methods so they would know which method s can throw exception and what exception they throw.
# annotating Scala method with @throwsclass someclass{ @throws (Classof[excepion]) def ascalamethod{throw New Exception ("Exception")}}
If you attempt the Ascalamethod from a Java class without wrapping it in a try/catch block, or declaring that your Jav A method throws an exception, the compiler would throw an eeor.
= new SomeClass (); try{ S.ascalamethod ();} catch (Exception e) { System.err.println ("caught the Exception"); E.printstacktrace ();}
Beginning Scala Study Note (9) Scala and Java interoperability