简体   繁体   中英

import class priority in scala vs java

I got stuck because of import class problem. In my case, my class has a dependency with Apache Common StringUtils , and there is a same name class( StringUtils ) in same package. (Main class has a dependency with Apache Common's StringUtils , and there is a StringUtils in same package with Main class. But it is compile error)

在此输入图像描述

I specified apache common's StringUtils with import syntax, but It seems shadowed by same package's StringUtils . Is it scala's language spec?

In Java, there is no problem. It works with Apache common's StringUtils. 在此输入图像描述

I suggest that you simple use the ability in scala to create an "alias", like:

import users.{UserPreferences => UPrefs}  // import and rename for convenience

( from scala-lang.org )

In other words: simply avoid the shadowing of that class name, by importing the library class under a different name.

您可以使用完全限定名称来使用Apache的StringUtils。

println(org.apache.commons.lang3.StringUtils.isEmpty(""))

That's because your compiler uses the closest class it can find to represent StringUtils . It can either be the one you wrote in your code or the one in org.apache but who knows? You yourself may not even be sure at some point! So you have to clarify that.

A class is actually defined using the whole package name and when you do an import it only allows you to use the shortcut ie StringUtils instead of org.apache.commons.lang3.StringUtils .

To counter that problem, several options:

  • static import with import org.apache.commons.lang3.StringUtils._ : here you can directly call the method isEmpty but the compiler won't find StringUtils per say
  • use the whole name in your call: println(org.apache.commons.lang3.StringUtils.isEmpty(...)) That way, no confusion possible
  • in Scala you have the possibility of defining alliasses. To do so, you have two options. Either at import time: import org.apache.commons.lang3.{StringUtils => ApacheStringUtils} or in your class: type ApacheStringUtils = org.apache.commons.lang3.StringUtils . For this kind of cases, option "at import time" is slightly more convenient and maybe even more efficient (you may replace the type you defined in your code at Runtime).

I would personnally prefer option 3.1 (when you create an alias at import time). This way, you code is clearer and you can call any function from StringUtils .

Another option is to import all members of StringUtils (something like static import in Java):

org.apache.commons.lang3.StringUtils._

Then you'd be able to directly call method:

println(isEmpty(""))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM