套件和匯入
Scala 使用套件來建立名稱空間,讓您可以模組化程式。
建立套件
套件是透過在 Scala 檔案最上方宣告一個或多個套件名稱來建立的。
package users
class User
一個慣例是將套件命名為包含 Scala 檔案的目錄相同。然而,Scala 與檔案配置無關。一個 package users
的 sbt 專案目錄結構可能如下所示
- ExampleProject
- build.sbt
- project
- src
- main
- scala
- users
User.scala
UserProfile.scala
UserPreferences.scala
- test
請注意 users
目錄位於 scala
目錄中,以及套件中有許多 Scala 檔案。套件中的每個 Scala 檔案都可以有相同的套件宣告。宣告套件的另一種方式是將它們巢狀在彼此之中
package users {
package administrators {
class NormalUser
}
package normalusers {
class NormalUser
}
}
package users:
package administrators:
class NormalUser
package normalusers:
class NormalUser
如您所見,這允許套件巢狀,並提供對範圍和封裝的更大控制。
套件名稱應全部使用小寫,如果程式碼是在有網站的組織內開發,則應採用下列格式慣例:<top-level-domain>.<domain-name>.<project-name>
。例如,如果 Google 有個名為 SelfDrivingCar
的專案,套件名稱看起來會像這樣
package com.google.selfdrivingcar.camera
class Lens
這可能會對應到下列目錄結構:SelfDrivingCar/src/main/scala/com/google/selfdrivingcar/camera/Lens.scala
。
匯入
import
子句用於存取其他套件中的成員(類別、特質、函式等)。存取同一個套件的成員不需要 import
子句。匯入子句具有選擇性
import users._ // import everything from the users package
import users.User // import the class User
import users.{User, UserPreferences} // Only imports selected members
import users.{UserPreferences => UPrefs} // import and rename for convenience
import users.* // import everything from the users package except given
import users.given // import all given from the users package
import users.User // import the class User
import users.{User, UserPreferences} // Only imports selected members
import users.UserPreferences as UPrefs // import and rename for convenience
Scala 與 Java 不同之處之一是匯入可以在任何地方使用
def sqrtplus1(x: Int) = {
import scala.math.sqrt
sqrt(x) + 1.0
}
def sqrtplus1(x: Int) =
import scala.math.sqrt
sqrt(x) + 1.0
如果發生命名衝突,而且您需要從專案的根目錄匯入某些內容,請在套件名稱前面加上 _root_
package accounts
import _root_.users._
package accounts
import _root_.users.*
注意:scala
和 java.lang
套件以及 object Predef
預設會匯入。