程式扎記: [Scala 常見問題] How to call main method of a Scala program from the main method of a java program?

標籤

2016年7月10日 星期日

[Scala 常見問題] How to call main method of a Scala program from the main method of a java program?

Source From Here
Question
Suppose I have a Scala class and a Java class in a Java project and the scala class is like below:
  1. class Sam {  
  2.   
  3.   def main(args: Array[String]): Unit = {  
  4.     println("Hello")  
  5.   }  
  6.   
  7. }  
How can I call it's main method from the main method of a java program which is present in the same project
How-To
Typically, main methods are static in Java, and in an object in Scala. This allows you to run them from the command line. Your code defines a class, not an object. I'd suggest changing your Scala code to:
  1. object Sam {  
  2.   def main(args: Array[String]): Unit = {  
  3.     println("Hello")  
  4.   }  
  5. }  
You can then call this from your Java main method as follows:
  1. class Foo  {  
  2.     public static void main(String[] args) {  
  3.         Sam.main(args);  
  4.     }  
  5. }  

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!