Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala import java package appending com

Tags:

java

scala

I'm working on a Scala project that is importing two java libraries. Through poor planning, the two java libraries have similar package names, one with com on the front, one without.

The problem is that Scala is looking for the package with com in front first, and telling me that the package doesn't exist. If I remove all references to the library with com in front of the package, the compile works.

To show an example that makes sense:

In foo.jar we have a package company.product.core

In bar.jar we have a package com.company.product.other.

If both jars are on the classpath, the line:

import company.product.core.ClassName

Fails with the error "value core is not a member of package com.companyname.product" If we remove bar.jar, the compile works fine.

Is Scala trying to save me from typing com.? Is there a way to tell it to import only what I tell it to?

like image 637
Jeff Avatar asked Jan 27 '10 16:01

Jeff


People also ask

Can we use Java package in Scala?

When you're writing Scala code and need to use a Java collection class, you can just use the class as-is. However, if you want to use the class in a Scala for loop, or want to take advantage of the higher-order functions on the Scala collections classes, you'll want to convert the Java collection to a Scala collection.

How do I use Scala packages?

Click on file, new then scala project and give it a name. To define a package in Scala you use the keyword package that is then followed by name of the package. To package your code you create a Scala object (. scala) and place it there then store it in your preferred folder in project structure.

How does import work in Scala?

Import in Scala Importing packages in Scala is more flexible than in other languages. We can place import statements anywhere in the code and even hide or rename members of packages when you import them. Note: Users can either import the package as a whole or some of its member methods, classes, etc.

How do I import shells to Scala?

You need to run console from within the sbt shell. Then, sbt will compile whatever is defined in funsets and automatically add it in your Scala shell. From there, you'll be able to do import funsets. _ .


1 Answers

Use _root_ prefix in import statements. It makes package resolution absolute.

import _root_.company.product.core.ClassName
import _root_.com.company.product.other.ClassName

Referring to you comment: with relative imports you could do something like this. It basically saves you some typing.

import _root_.company.product.core
import ClassAFromCore
import ClassBFromCore
like image 141
Juha Syrjälä Avatar answered Sep 22 '22 20:09

Juha Syrjälä