Interoperability with Java

Source: Internet
Author: User

1. Using the Scala class in Scala

If you create a Scala class in a separate file, you can easily use them, just like (without explicit compilation) in a Scala script. However, if you want to use a Scala class in a compiled Scala or Java code, you must compile it.

Examples are as follows:

 Package Com.cn.peng class Person (Val firstname:string, Val lastname:string) {    = firstName + "" + LastName}
 Package Com.cn.peng class Dog (name:string) {    = name}

Here's a script that uses the above two classes:

 Package Com.cn.pengobject Use {  def main (args:array[string]) {    new person ("George", "Washington" )        = List (newnew Dog ("Clode"),        newnew Dog (" Searcher "))            printf ("%s had several dogs%s ... ", George,geogesdogs mkstring", ")  }    } 

The script produces the following output:

George Washington had several dogs captain, Clode, Forester, Searcher ...
2. Using Java classes in Scala

You can use Java classes directly in Scala. If the Java class you want to use is part of a standard JDK, just use it. If it is not in Java.lang, it is necessary to import the class package. The following uses the Java.util and Java.lang.reflect packages:

 Package Com.cn.peng Import java.util.Date Import  extends  App {    println (new  Date ())        =  Getclass.getmethods ()    = println (Method.getname ())}}

The results of the program run as follows:

Today is Sat 16:53:55 CSTmaindelayedendpoint$com$cn$peng$usejdkclasses$1Argsdelayedinitscala $APP $_setter_$executionstart_$eqexecutionstartscala$app$$_argsscala$app$ $initCodemethodsscala $app$$_args_$ eqscala$app$_setter_$scala$app$ $initCode _$eqwaitwaitwaitequalstostringhashcodegetclassnotifynotifyall

If you want to use a Java class that you created yourself, or from a third party, make sure that Scalac's classpath points to the byte-code location. Suppose we have the following Java files:

 Package Investments;  Public enum Investmenttype {    short_term,    BOND,    STOCK,    Real_estate,    commodities,    collectibles ,    Mutual_funds}
 package   investments;  public  class   investment {  String Investmentname;         private   Investmenttype Investmenttype;  public   investment (String name,        Investmenttype type) {investmentname  = name;    Investmenttype  = type;  public  int  yield () {return  0 

Using these classes in Scala code is the same as using Scala classes. Here is an example of creating a investment instance in Scala:

 Package Com.cn.peng Import Investments._object useinvestment {    def main (args:array[string]) {      new investment ("XYZ Corporation ", Investmenttype.stock)      println (Investment.getclass ())    }}

The results of the operation are as follows:

class Investments. Investment

The yield () method of the investment class needs to be used with caution. If the Java code has a method or field name (such as trait or yield, etc.) in the Scala keyword conflict, calling them causes the Scala compiler to die. For example, the following code is not possible:

      Val theYield1 = Investment.yield   //error      //error

Fortunately, Scala offers a solution. By putting the conflicting variables/methods in the inverted quotation marks, you can bypass the problem. Change the code to make the above two calls work:

      Val theYield1 = investment. ' Yield '         = investment. ' Yield ' ()
3. Using the Scala class in Java

Scala provides complete two-way interoperability with Java. Because Scala compiles into bytecode, it's fairly easy to use the Scala class in Java. By default, Scala does not follow the JavaBean convention, and @scala.reflect.beanproperty this annotation to generate JavaBean-predetermined getter and setter. You can also inherit Java classes from the Scala class, but to run Java code that uses the Scala class, you need to have Scala-library.jar in Classpath. In this section, we will see how the architecture of Scala will behave differently on the Java side.

3.1 Scala classes with common functions and higher-order functions

Scala classes that follow standard Java constructs are fairly straightforward and easy to use on the Java side. We write a Scala class:

 Package Automobiles class Car (Val year:int) {    private[this] var miles:int = 0        + = Distance}         = ' year: ' + year + ' miles: ' + miles}

Here's a Java class that uses this Scala class:

 Package Com.cn.peng; Import automobiles. Car;  Public class Usecar {    publicstaticvoid  main (string[] args) {        new Car ();        SYSTEM.OUT.PRINTLN (car);        Car.drive (ten);        SYSTEM.OUT.PRINTLN (car);}    }

The results of the program run as follows:

year:2014 miles:0miles:10

Using the Scala class in Java is fairly straightforward. However, not all Scala classes are so friendly. For example, if the Scala class has methods to receive closures, these methods are not available in Java, because Java does not currently support closures. The following equipment class's simulate () method is not available for Java, but we can use the run () method:

 Package Com.cn.peng class Equipment {    //notusable from Java  def Simulate (input:int) (Calculator:int = int): int = {    //...     Calculator (input)  }    def run (duration:int) {    println ("Running")     // ...   }}

Therefore, when designing the API, if the class is primarily for Java use, provide a general function while providing a higher-order function, making this class fully available to Java.

3.2 Working with trait

A trait without a method is a simple interface at the byte-code level. Scala does not support the interface keyword. Therefore, if you want to create an interface in Scala, create a trait that is not implemented. Here is an example of a Scala trait, which is also an interface:

 Package com.cn.pengtrait Writable {    def wirte (message:string): Unit}

There is an abstract method in the above trait, and the class that is mixed with this trait should implement this method. On the Java side, writable can be seen as the same as other interfaces; it has no dependency on Scala at all. So, it can be implemented like this (implement):

 Package Com.cn.peng;  Public class Implements writable{    @Override    publicvoid  wirte (String message) {        //  TODO auto-generated method stub            }}

However, if trait has a method implementation, then the Java class cannot implement this trait/interface, although they can use it. Therefore, you cannot implement the following printable in Java, but you can hold a printable reference:

 Package com.cn.pengtrait Printable {    //default printNothing}

If you want the Java class to implement trait, let it be pure; in other words, don't implement it. In this case, any public implementation should be placed in the abstract base class, not in the trait. However, if you just want Java classes to use trait, there is no limit.

3.3 Singleton objects and associated objects

Scala compiles an object (a singleton or associated object) into a "singleton class"-the class has a special $ character at the end of its name. Thus, the object shown below is a single, which produces a class name of single$. However, Scala handles singleton and companion objects somewhat differently, as you can see later.

Scala compiles a singleton object into a singleton class (which uses a static method of Java), and also creates a generic class that passes the call to the Singleton class. So, the following code creates a singleton object single, and Scala creates two classes: single$ and the class to pass the call to.

 Package Com.cn.pengobject Single {    def greet () {println ("Hello")}}

Using the above singleton object in Java is like using the Java class of the static method, as follows:

 Package Com.cn.peng;  Public class SingleUser {    publicstaticvoid  main (string[] args) {        Single.greet ( );    }}

The output of the above code is as follows:

Hello from single

If the object is associated with a class of the same name, Scala creates two classes, one class representing the Scala class (Buddy in the following example), and another class that represents the associated object (buddy$ in the following example):

 Package Com.cn.peng class Buddy {    def greet () {println ("Hello from Buddy class")}}object Buddy {    def greet () {println (" Hello from Buddy object ")}}

The associated class can be accessed directly using the name of the class. Access to the companion object requires the use of a special symbolic module$, as shown in the following example:

 Package Com.cn.peng;  Public class Buddyuser {    publicstaticvoid  main (string[] args) {        new  Buddy (). greet ();        buddy$. Module$.greet ();    }}

The output is as follows:

class Hello from Buddy object
4. Inheriting classes

Scala classes can inherit Java classes and vice versa. In most cases, this should suffice. As discussed earlier, if the method receives closures as parameters, it can be cumbersome to rewrite them. Exceptions are also the problem.

Scala has no throws words. In Scala, any method can throw an exception without explicitly declaring it as part of a method signature. However, if you rewrite this method in Java, trying to throw an exception, you will get into trouble. For example, let's say that Scala defines bird:

 Package Com.cn.peng Abstract class Bird {    def fly ();     // ...}

There is another class ostrich:

 Package Com.cn.peng class extends Bird {    def fly () {      thrownew  noflyexception    }      //...}

Where noflyexception is defined as follows:

 Package Com.cn.peng class extends exception{}

In the above code, Ostrich fly () throws an exception without any problems. However, if you want to implement a flightless bird in Java, there will be trouble as follows:

 Package Com.cn.peng;  Public class extends bird{    publicvoidthrows  noflyexception {        throw New noflyexception ();    }     // ...}

First, if you just throw an exception, Java will error "unreported exception noflyexception;must be caught or declared to be thrown." Once the throws clause is added, Java will error "Exception Noflyexception is not compatible with throws clause in Bird.fly ()".

Even though Scala is flexible, it's not always necessary to specify which exceptions to throw, but to inherit these methods in Java, tell the Scala compiler to record the details in the method signature. Scala provides a backdoor for this: defining @throws annotations.

Although Scala supports annotations, it does not provide the syntax for annotations. If you want to create your own annotations, you have to do it in Java. @throws is a good note that represents a controlled exception thrown by a method. So, for us, to implement Penguin in Java, we have to change the bird to this:

 Package Com.cn.peng Abstract class Bird {  @throws(Classof[noflyexception]) def fly ();     // ...}

Now, with the code above, the Scala compiler puts the necessary signatures in the bytecode for the fly () method. After this modification, the Java class Penguin can be compiled normally.

Interoperability with Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.