Package and Namespace

本文介绍了Scala中包管理的概念及其灵活性,对比Java提供了更多的定制选项。文章详细解释了如何使用传统Java语法及块结构语法定义包,并展示了如何通过单一声明创建多个嵌套包。此外,还讨论了在不同情况下使用单独包声明的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Scala adopts the package concept that Java uses for namespaces, but Scala offers more flexibility. Filenames don’t have to match the type names and the package structure does not have to match the directory structure. So, you can define packages in files independent of their “physical” location.

1. Defines class in a package using the conventional Java syntax

// src/main/scala/progscala2/typelessdomore/package-example1.scala
package com.example.mypkg
class MyClass {
    // ...
}

2. Defines classes in packages using block-structured syntax

// src/main/scala/progscala2/typelessdomore/package-example2.scala
package com {
    package example {
        package pkg1 {
            class Class11 {
                def m = "m11"
            }
            class Class12 {
                def m = "m12"
            }
        }
        package pkg2 {
            class Class21 {
                def m = "m21"
                def makeClass11 = {
                    new pkg1.Class11
                }
                def makeClass12 = {
                    new pkg1.Class12
                }
            }
        }

        package pkg3.pkg31.pkg311 {
            class Class311 {
                def m = "m21"
        }
}

The package pkg3.pkg31.pkg311 shows that you can “chain” several packages together in one statement. It is not necessary to use a separate package statement for each package.

3. Using separate package name

However, there is one situation where you might use separate statements.

// src/main/scala/progscala2/typelessdomore/package-example3.scala
// Bring into scope all package level declarations in "example".
package com.example
// Bring into scope all package level declarations in "mypkg".
package mypkg
class MyPkgClass {
    // ...
}

If you have package-level declarations, like types, in each of several parent packages that you want to bring into scope, use separate package statements as shown for each level of the package hierarchy with these declarations. Each subsequent package statement is interpreted as a subpackage of the previously specified package, as if we used the block-structure syntax shown previously.

4. Note

Packages can not be defined within classes and objects, which wouldn’t make much sense anyway.

Ref

《Programming Scala》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值