通配符导入Java和Scala中的用法 [英] Wildcard imports usage in Java and Scala

查看:107
本文介绍了通配符导入Java和Scala中的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我经常听到你永远不应该使用通配符导入的陈述。所以我想向社区询问此事。是否真的永远不会在Java生产代码中使用通配符导入,无论如何?这条规则有例外吗?我对您的个人经历和意见感兴趣。您是否在生产代码中使用它们并将其推荐给其他人?你如何使用它们 - 你能推荐最好的方法吗?

Recently I have heard statements like "you should never use wildcard imports" too often. So I want to ask community about this. Should wildcard imports really never ever be used in Java production code, no matter what? Are there exceptions to this rule? I interested in your personal experience and opinion. Do you use them in your production code and would you recommend it to others? How do you use them - can you recommend the best way to make it.

从Scala的角度看它也很有趣。 Scala也是如此吗?或者Scala中的通配符导入应仅用于演示幻灯片和SO答案吗?

It also interesting to look at it from Scala perspective. Is the same applies to Scala? Or wildcard imports in Scala should be only used in presentation slides and SO answers?

如果您要查看

If you will look at scalaz page, for example, they recommend usage of wildcard imports like:

import scalaz._
import Scalaz._   

我认为考虑隐式转换也很重要通常使用通配符导入。

I think it also important to consider implicit conversions that are normally imported with wildcards.

推荐答案

在Scala中,通配符导入是必须的,因为许多库希望它们的隐式转换是范围,但它们并不总是方便地命名。所以,

In Scala, wildcard imports are a must, since many libraries expect their implicit conversions to be in scope, but they're not always conveniently named. So,

import collection.JavaConversions._

是一个好主意,而

import collection.JavaConversions.{asJavaConcurrentMap,enumerationAsScalaIterator,...}

令人难以置信的尴尬。更好的是,在Scala中你可以将你的导入放在任何范围内:

is incredibly awkward. Better yet, in Scala you can put your imports in any scope:

package mypackage {
  class MyClass {
    def myGraphicalWidgetHandler {
      import java.awt._
      ...
    }
    ...
  }
  ...
}

这确实有助于在整个文件中保持命名空间的混乱。并且您可以有选择地重命名您知道会冲突的部分导入:

which really helps keep the namespace clutter down throughout the whole file. And you can selectively rename parts of the import that you know will conflict:

import java.awt.{List => AwtList, _}

相比之下,在Java中,您被限制为全球导入范围,并且你不能重命名他们;你也没有隐含的转换,所以只需要提取你正在寻找的东西。另一方面,您拥有强大的IDE支持,可帮助您找到您正在寻找的类,并为您导入它。所以对于Java来说,有一个合理的论据是你应该让你的IDE接受你需要的东西,而不是你决定抓住所有东西。就个人而言,我仍然发现这太尴尬了,大部分时间只使用通配符导入。

In contrast, in Java, you're restricted to global scope for imports, and you can't rename them; you also don't have implicit conversions, so it's okay to only pull in those things that you're looking for. On the other hand, you have powerful IDE support that will help find the class that you're looking for and import just it for you. So for Java, there's a reasonable argument to be made that you should let your IDE pull in just what you need rather than you deciding to grab everything. Personally, I still find this too awkward and just use wildcard imports most of the time.

这篇关于通配符导入Java和Scala中的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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