简体   繁体   English

如何调用 Scala 中的方法

[英]How to Call Methods in Scala

I have written some code in scala and created one method inside that now i want to call this method in another program but I'm not not getting any result after calling this method.我在 scala 中编写了一些代码,并在其中创建了一个方法,现在我想在另一个程序中调用此方法,但调用此方法后我没有得到任何结果。

First Program第一个程序

object helper_class {
  def driver {
    def main(args: Array[String]) {
      val sparksession = SparkSession.builder().appName("app").enableHiveSupport().getOrCreate();
      val filepath: String = args(0)
      val d1 = spark.sql(s"load data inpath '${args(0)}'  into table databasename.tablename")
      //some more reusable code
    }
  }
}

second Program第二个程序

import  Packagename.helper_class.driver
object child_program {
  def main(args: Array[String]) {
    driver //I want to call this method from  helper_class
  }
}

if I'm removing def main(args: Array[String]) from 1st code its giving error near args(0) as args(0) not found args(0) I am planning to pass as spark-submit can someone please help me how should i Implement this.如果我从第一个代码中删除def main(args: Array[String])它在args(0)附近给出错误,因为args(0)未找到args(0)我打算通过 spark-submit 有人可以帮忙吗我应该如何实现这一点。

The main method is your entry point to run a program. main方法是您运行程序的入口点。 It can't be wrapped within another method.它不能被包装在另一个方法中。 Thus, you can't wrap it within another method.因此,您不能将其包装在另一种方法中。

I think what you are trying to do, is to load some Spark setup code and then use that "driver" to do something else... This is my best guess on how that could work我认为您正在尝试做的是加载一些 Spark 设置代码,然后使用该“驱动程序”做其他事情......这是我对它如何工作的最佳猜测

object ChildProgram {
  def main(args: Array[String]): Unit = {
    val driver = Helper.driver(args)
    // do something with the driver
  }
}



object Helper {
    def driver(args: Array[String]) = {
      val sparksession = SparkSession.builder().appName("app").enableHiveSupport().getOrCreate()
      val filepath: String = args(0)
      val d1 = spark.sql(s"load data inpath '${args(0)}'  into table databasename.tablename")
      //some more reusable code

      // I am assuming you are going to return the driver here
    }
}

That said, I would highly recommend reading a bit on Scala before attempting to go down that route, because you are likely to face even more obstacles.也就是说,我强烈建议您在尝试 go 之前在 Scala 上阅读一些内容,因为您可能会面临更多障碍。 If I am to recommend a resource, you can try the awesome book "Scala for the Impatient" which should get you up and running very quickly.如果我要推荐一个资源,你可以试试这本很棒的书“不耐烦的 Scala”,它会让你快速上手并运行起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM