我可以在Scala中同时从多个包中导入吗? [英] Can I import from multiple packages all at once in Scala?

查看:159
本文介绍了我可以在Scala中同时从多个包中导入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在特定项目中我的Scala文件的开头,我经常有这样的行:

At the beginning of my Scala files in a particular project, I often have lines like these:

package com.mycompany
package subproject

import common._
import uiutils._
import databinding._
import modeling._

有没有办法创建一个对象 ProjectImports (或包对象) preimports所有这些导入,然后我可以简单地写

Is there a way to create an object ProjectImports (or package object) that "preimports" all of these imports such that I can then simply write

import ProjectImports._

而不是整个列表,在我的每个其他项目文件中?

instead of the whole list, in each of my other project files?

是这与 scala 包在 Predef 中的导入方式有关,其中包含 scala .package`

Is this related to the way the scala package is imported in Predef with scala.`package`?

推荐答案

如果您需要的所有导入都是某些特征的成员,则可以轻松完成。如果您有多个具有函数,内部类等的特征,则可以创建从所有特征继承的对象。所以他们所有的东西都可以用简单的导入MyObject ._ 导入。以这种方式导入类变得有点棘手 - 你必须为每个类创建一个类型成员。

You can do it easily if all imports you needed are members of some traits. If you have several traits with functions, inner classes etc. you can create object inherited from all of them. So all their stuff can be imported with simple import MyObject._. Importing class in this way became a bit tricky - you have to create a type member for each class.

有关此技术的更多示例,请参阅Casbah 导入对象 Scalaz对象

For more examples of this technique see Casbah Imports object and Scalaz object in scalaz project.

这篇关于我可以在Scala中同时从多个包中导入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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