Sunday, March 21, 2010

Scala and Java interoperability

//ScalaClass.scala

class ScalaClass (val creater:String){
override def toString
="I am ScalaClass created by "+creater
}

//CallScala.java
//This java class uses ScalaClass

public class CallScala {
public static void main(String[] args) {
ScalaClass scalaClass
= new ScalaClass("Java");
System.out.println("Calling scala from java");
System.out.println(scalaClass);
}

public void pingMeFromScala(){
System.out.println("Hey scala pinged me");
}

}

//CallJava.scala
//This scala class uses the java class CallScala

object CallJava
{
def main
(args:Array[String]){
val callScala
= new CallScala
callScala
.pingMeFromScala
}
}


#Steps

1)scalac ScalaClass.scala

2)javac CallScala.java

3)scalac CallJava.scala

//Include scala-library.jar in classpath if you are usinf a scala class in java
4)java -cp /home/byju/scala-2.8.0.Beta1/lib/scala-library.jar:. CallScala

// You can use scala to run a java class
5)scala CallScala

6)scala CallJava
// You can use java to run a scala class by including scala-library.jar in classpath

7)java -cp /home/byju/scala-2.8.0.Beta1/lib/scala-library.jar:. CallJava