Scala library provides a set of Java annotations for interoperability. We will introduce these notes below
1, Java modifiers
Java modifiers: For those who are not very common characteristic of Java, Scala using annotations instead of modifier keys.
// JVM中将成为volatile的字段
@volatile var done = false
// 在JVM中将成为transient字段,该字段不会被序列化。
@transient var recentLookups = new HashMap[String, String]
@strictfp def calculate(x: Double) = ...
@native def win32RegKeys(root: Int, path: String): Array[String]
2, marker interface
Marker interface: Scala @cloneable with annotations and @remote instead java.rmi.Remote Cloneable and "marker interface" can be cloned to mark objects and remote objects
@cloneable class Employee
3, abnormal subjects
Unlike Scala, Java compiler will track the subject exception: Unchecked exceptions. If you call Scala code from Java method signature should contain those subjects exception may be thrown. With @throws annotation to generate the correct signature.
class Book {
@throws (classOf[IOException]) def read(filename: String) { ... }
...
}
Java版本的方法签名:
void read(String fileName) throws IOException
// 如果没有@throws注解,Java代码将不能捕获该异常
try {//Java代码
book.read("war-and-peace.txt");
} catch (IOException ex) {
...
}
Namely: Java compiler at compile time period need to know read method can throw an IOException, or Java will refuse to catch the exception.
Scala
class A{
def play() = {
throw new IOExcetion()
}
}
Java
class B{
public static void main(String[] args){
A.play()
}
}
Thrown in Scala, call this method in Java, because it is Scala syntax, Java does not detect an exception is thrown, you need to add an exception comment
Reproduced in: https: //www.jianshu.com/p/0ce7b51f50a6