scala导入java类,通配符导入Java和Scala中的用法

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.

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.

解决方案

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._

is a great idea, whereas

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

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, _}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值