1

Am trying to learn Scala. With whatever i could look into so far, i see it mentioned that Scala is pretty compatible with Java. "You can call the methods of either language from methods in the other one". But i just couldn't find a suitable example of a custom Java class being imported into a Scala and used. So am starting to wonder if this is even possible? Could you please advise this newbie?

Am using notepad, and not an editor (had run into many issues in using Eclipse).

I have an Employee class in Java:

package Emp;
class Employee {
    String name;
}

And am trying to have this imported in my scala class

import Emp._

object Emp extends Employee{
     .......}  

But this just does not compile. Wonder if am missing something in concept or syntax; please help.

4
  • 1
    Please provide the exact error etc. Of course you can import Java classes. Commented Oct 27, 2014 at 14:29
  • It reads: "....: error: not found: type Emp import Emp._" And there is a small "^" pointing to Emp Commented Oct 27, 2014 at 14:31
  • It should be class Emp extends Employee. An companion object in Scala is somewhat different than a class! Commented Oct 27, 2014 at 14:55
  • @GyroGearless, there is no reason why Emp can't be object. Companion objects is a different matter. Commented Oct 27, 2014 at 15:27

1 Answer 1

5

Yes, it is possible. Your Employee class, however, is not public. Add a public modifier, and it should work.

You should also check that your classpath is correct. The best way to ensure that everything is right is to use a build tool like SBT. If you use SBT and follow its conventional directories layout (Scala sources in src/main/scala, Java sources in src/main/java), then Scala classes will be able to see their Java counterparts and vice versa effortlessly.

However, according to the little source code you presented, you can also have a name conflict. You have a package Emp and an object named Emp; packages and classes/objects share namespace in Scala and Java, so you can't have a package and a completely unrelated object with the same name at the same time. I'd recommend renaming the package into something more idiomatic.

See this gist. The file names are mangled because Github does not allow slashes in file names (so I replaced them with dashes), but you get the main idea, I believe.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.