1. Translating Java Classes to Scala Classes

  Example 1:

# a class declaration in Java
public class Book{} # Scala equivalent of a class declaration
class Book

  Example 2:

# a Java class with a Construtor
public class Book{
private final int isbn;
private final String title; public Book(int isbn, String title){
this.isbn = isbn;
this.title = title;
} public int getIsbn(){
return isbn;
} public String getTitle(){
return title;
}
} # Scala equivalent
class Book(val isbn: Int, val title: String)

  Example 3:

# constructor calling superclass in Java
public class NonFiction extends Book{
public NOnFiction(String title){
super(title);
}
} # Scala equivalent
class NonFiction(title: String) extends Book(title)

  Example 4:

# mutable instance variable in Java
public class Book{
private String title = "Beginning Scala"; public String getTitle(){
return title;
} public void setTitle(String t){
title = t;
}
} # Scala equialent
class Book{
var title = "Beginning Scala"
}

  Example 5:

# immutable instance variable in Java
public class Book{
private final int isbn = ; public int getIsbn(){
return isbn;
}
} # Scala equivalent
class Book{
val isbn =
}

  Translating Java imports to Scala imports:

# import in Java
import com.modA.ClassA;
import com.modB.ClassB1;
import com.modB.ClassB2;
import com.modC.*; # import in Scala
import com.modA.ClassA
import com.modB.{ClassB1,ClassB2} // you can stack multiple imports from the same package in braces
import com.modC._ // underscore in Scala imports is equivalent of * in Java imports

  Example 6:

# Java class with multiple constructors
public class Book {
private Integer isbn;
private String title;
public Book(Integer isbn) {
this.isbn = isbn;
}
public Book(Integer isbn, String title) {
this.isbn = isbn;
this.title = title;
}
public Integer getIsbn() {
return isbn;
}
public void setIsbn(Integer isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}} # refactoring
class Book(var isbn: Int, var title: String)

  If you create the Book instance with a construtor that takes a single "title" parameter, you will get an error.

scala> val book = new Book("test")
<console>:: error: not enough arguments for constructor Book: (isbn: Int, title: String)Book.
Unspecified value parameter title.
val book = 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(,title)
| }
defined class Book
scala> val book = new Book("test")
book: Book = Book@1ab0286
scala> book.isbn
res2: Int =
scala> book.title
res3: String = 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 have Java-style getters and setters is to annotate the field with scala.beans.BeanProperty. In this way, you can interact with a Java calss or library that accepts only classes that conform to the JavaBean specification.

scala> import scala.beans.BeanProperty
import scala.beans.BeanProperty scala> 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);
public void setIsbn(int);
public java.lang.String title();
public void title_$eq(java.lang.String);
public void setTitle(java.lang.String);
public int getIsbn();
public java.lang.String getTitle();
public Book(int, java.lang.String);
}

  The methods getTitle,setTitle,getIsbn,setIsbn have all been generated because of the @BeanProperty annotation. Note that use the @BeanProperty annotation on your fields, also making sure you declare each field as a var. If you declare your fields a type val, the setter 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 declaration

public interface Book{
public abstract boolean isBestSeller();
} # Scala equivalent
trait Book{ def isBestSeller: Boolean}

  Note that in scala, if there is no  = assignment, then the methods denoted with a def keyword or the functions denoted with a val keyword are abstract. That means if there's no definition provided with =, then it's automatically abstract.

# a concrete Java method
public String someMethod(int arg1, boolean arg2){return "voila"} # Scala equivalent
def someMethod(arg1: Int, arg2: Boolean) :String = "volia" # an abstract Java method
abstract int doTheMath(int i) # Scala equivalent
def doTheMath(i: Int): Int

  Example: you need to be able to user an add method from a Java application:

# a Scala trait
trait Computation{def add(a: Int, b:Int) = a + b} # a Java application
public class DoTheMath{
public static void main(String[] args){
DoTheMath d = new DoTheMath();
}
}

  Java class DoTheMath cannot implement the trait Computation because Computation is not like a regular Java interface. To be able to use the implemented method add of a Scala trait Computation from Java class DoTheMath, you must wrap the trait Computation in a Scala class.

# Scala class that wraps the trait Computation
class JavaInteroperableComputation extends Computation # accessing the add method of the Scala trait from Java class
public class DoTheMath extends JavaInteroperableComputation{
public static void main(String[] args){
DoTheMath d = new DoTheMath();
d.add(,);
}
}

  Note that wrap you scala traits with implemented behavior in the Scala class for its Java callers.

4. Java static members and Scala objects

# a singleton in Scala
public class Book{
private static Book book;
private Book(){}
public static synchronized Book getInstance(){
if(book == null){
book = new Book();
}
return book;
}
} # Scala equivalent, object can extend interfaces and traits
object Book{}

  The companion object enables storing of static methods and from this, you have full access to the class's members, including private ones. Scala alows you to declare both an object and a class of the same name, placing the static members in the object and the instance members in the class.

# Java class with instance and static methods
public class Book{
public String getCategory(){
return "Non-Fiction";
} public static Book createBook(){
return new Book();
}
} # Scala equivalent
class Book{
def getCategory() = "Non-Fiction"
} object Book{
def createBook() = new Book()
}

5.  Handling Exceptions

# a Scala method that throws an Exceotion
class SomeClass{
def aScalaMethod{ throw new Exception("Exception")}
} # calling a Scala method from a Java class
publc static void main(String[] args){
SomeClass s = 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 you Scala methods, add the @throws annotation to your Scala methods so they will know which methods can throw exception and what exception they throw.

# annotating Scala method with @throws
class SomeClass{
@throws(classOf[Excepion])
def aScalaMethod{ throw new Exception("Exception")}
}

  If you attempt to call aScalaMethod from a Java class without wrapping it in a try/catch block, or declaring that your Java method throws an exception, the compiler will throw an eeor.

#calling annotated aScalaMethod from Java
SomeClass s = 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的更多相关文章

  1. Beginning Scala study note(8) Scala Type System

    1. Unified Type System Scala has a unified type system, enclosed by the type Any at the top of the h ...

  2. Beginning Scala study note(6) Scala Collections

    Scala's object-oriented collections support mutable and immutable type hierarchies. Also support fun ...

  3. Beginning Scala study note(3) Object Orientation in Scala

    1. The three principles of OOP are encapsulation(封装性), inheritance(继承性) and polymorphism(多态性). examp ...

  4. Beginning Scala study note(2) Basics of Scala

    1. Variables (1) Three ways to define variables: 1) val refers to define an immutable variable; scal ...

  5. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  6. Beginning Scala study note(1) Geting Started with Scala

    1. Scala is a contraction of "scalable" and "language". It's a fusion of objecte ...

  7. Beginning Scala study note(7) Trait

    A trait provides code reusability in Scala by encapsulating method and state and then offing possibi ...

  8. Beginning Scala study note(5) Pattern Matching

    The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters ...

  9. Scala 安装 Exception in thread "main" java.lang.VerifyError: Uninitialized object exists on backward branch 96

    windows下载安装完最新版本的Scala(2.12.4)后,终端如下错误 C:\Users\Administrator>scala -versionException in thread & ...

随机推荐

  1. visio二次开发——图纸解析之形状

    今天有空,下班前补齐解析visio图形形状的方法,包含图形背景色.字体颜色.备注信息.形状数据取值. /// <summary> /// 设置形状的选择属性 /// </summar ...

  2. Android常用组件之AutoCompleteTextView

    安卓组件中,凡是需要配置数据的组件,一般都是用Adapter配置. AutoCompleteTextView的使用方法与ListView类似,也是用setAdapter来设置数据. MultiAuto ...

  3. touch

    Linux touch 命令   在 Linux 下运用 touch 命令创建一个空文件.当然我们也可以使用其他命令例如 vi, nano 或是任意一个编辑工具来实现.但是你可能需要更多的步骤来完成操 ...

  4. Ruby安装Scss

    Ruby安装Scss 引言 已经许久不写HTML了,今天有点以前的东西要改.但是刚装的Windows10,已经没有以前的Web开发环境了.只好重新安装. 结果Webstorm装好后配置Scss出现错误 ...

  5. Python - 类与对象的方法

    类与对象的方法

  6. 怎样在Windows资源管理器中添加右键菜单以及修改右键菜单顺序

    有时,我们需要在Windows资源管理器的右键菜单中添加一些项,以方便使用某些功能或程序. 比如我的电脑上有一个免安装版的Notepad++,我想在所有文件的右键菜单中添加一项用Notepad++打开 ...

  7. react+redux官方实例TODO从最简单的入门(5)-- 查

    上一篇文章<改>实现了,最后一个功能--<查>! 这个查是稍微要复杂一点的功能,官方实现的就是一个过滤数组的效果,然后展示出来,这里有3个状态,all,completed,ac ...

  8. mysql使用load导入csv文件所遇到的问题及解决方法

    使用navicat的客户端插入csv的数据文件,有一种非常简单的方式,即使用导入向导,直接根据数据匹配即可. 使用load的方式. 由于本项目中插入数据表量大而且格式统一,故首先使用创建字段creat ...

  9. 【Winform】使用BackgroundWorker控制进度条显示进度

    许多开发者看见一些软件有进度条显示进度,自己想弄,项目建好后发现并没有自己想象中的那么简单...看了网上很多教程后,写了一个小Demo供网友们参考~~,Demo的网址:http://pan.baidu ...

  10. Unhandled Exception:System.DllNotFoundException: Unable to load DLL"**":找不到指定的模块

    在项目中使用C#代码调用C++ DLL时.常常会出现这个问题:在开发者自己的电脑上运行没有问题,但是部署到客户电脑上时会出现下面问题: Unhandled Exception:System.DllNo ...