5122014009
5122014009

Reputation: 4092

Is it possible to import custom java classes into Scala?

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.

Upvotes: 1

Views: 10959

Answers (1)

Vladimir Matveev
Vladimir Matveev

Reputation: 127771

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.

Upvotes: 5

Related Questions