Scala 类顶部和内部的 Scala 导入语句 [英] Scala import statement at top and inside scala class

查看:57
本文介绍了Scala 类顶部和内部的 Scala 导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala中这两种导入策略的区别是什么

In scala what is the difference between these two import strategies

选项 1

import com.somepackage

class MyClass {
  //further code
}

选项 2

class MyClass {
  import com.somepackage
  //further code
}

推荐答案

在 Scala 中,import 是词法范围的.imported 标识符仅在它们 imported 的范围内可见.

In Scala, imports are lexically scoped. imported identifiers are only visible within the scope they were imported in.

在第一种情况下,作用域是文件,因此 import 将在整个文件中可见,但在其他文件中不可见.在第二种情况下,作用域是类,所以 import 将在整个类中可见,但在同一文件中的其他类中甚至都不可见(当然除了嵌套在 MyClass 中的类).

In the first case, the scope is the file, so, imports will be visible in the entire file, but not in other files. In the second case, the scope is the class, so imports will be visible in the entire class, but not in other classes even in the same file (except of course classes nested within MyClass).

您还可以将 import 的范围限制为单个方法甚至单个块(!)

You can also limit the scope of an import just to a single method an even a single block(!)

class Foo {
  def bar {
    // do something
    {
      import baz.quux.Frotz
      // use Frotz
    }
    // Frotz not visible here
  }
}

这是 Scala 的规律性、正交性和简单性的一个很好的例子.例如.在 Java 中,块为局部变量创建作用域,但不为 imports(或方法或其他任何东西)创建作用域.在 Scala 中,块创建作用域.时期.没有例外,没有极端情况.

This is a nice example of Scala's regularity, orthogonality and simplicity. E.g. in Java, blocks create scopes for local variables but not for imports (or methods or anything else). In Scala, blocks create scopes. Period. No exceptions, no corner cases.

import 位于大括号之间,因此它仅在大括号之间可见.它只是满足您的期望.

The import sits in between the curly braces, ergo it is only visible between the curly braces. It just does what you expect.

这篇关于Scala 类顶部和内部的 Scala 导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆