如何在Scala对象中访问嵌套函数

时间:2019-06-24 22:09:15

标签: scala apache-spark

我正在尝试访问嵌套函数。我可以访问func1,但是尝试访问func2时遇到问题。

//试图调用不同类中的方法

val t1 = test
t1.func1()
t1.func1(df).func2("test")

object test {
    def func1 (df: dataframe): tt = {

      def func2 (ab: String): String =  {
        // do something
      } else {
        // do nothing
      }

      def func3 (ab2: String): String = {
        //do something
      } else {
        // do nothing
      }

    }

  val t1 = test
  t1.func1()
  t1.func1(df).func2("test")

我希望没有任何错误地访问func2

2 个答案:

答案 0 :(得分:4)

您可以考虑将--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-6-b37c638b6114> in <module> 2 ----> 3 for i, data in enumerate(trainloader, 0): 4 inputs, labels = data[0], data[1] # ... IndexError: Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 99, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 99, in <listcomp> samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/lib/python3.6/site-packages/torchvision/datasets/mnist.py", line 95, in __getitem__ img = self.transform(img) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 61, in __call__ img = t(img) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 164, in __call__ return F.normalize(tensor, self.mean, self.std, self.inplace) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 208, in normalize tensor.sub_(mean[:, None, None]).div_(std[:, None, None]) IndexError: too many indices for tensor of dimension 0 等同于嵌套变量。您无法在其父函数之外访问此函数。

尝试改变一些方法以使该示例更加明显:

func2

您希望能够在这里访问object test { def func1 (df: dataframe): String = { val data = "hi" "bye" } } val t1 = test t1.func1(df).data 吗?

如果您尝试在data之外引用func2,则会收到编译器错误。

如果您需要访问func1并且没有任何其他限制,建议您在func2范围之外进行定义。

答案 1 :(得分:3)

closure属性可防止从封闭范围之外访问捕获的标识符。使用对象或类而不是函数并适当地重载将使内部作用域可访问。

object test {

    case class func1(df: dataframe){

        def apply(..)= {..}

        def func2 (ab: String): String =  {..}
        def func3 (ab2: String): String = {..}
   }
}