- Is it possible to import custom java classes into Scala?
- 1 Answer 1
- Packaging, Importing and Package Objects in Scala
- 2. Importing in Scala
- 2.1. Basic Import
- 2.2. Aliasing Imports
- 2.3. Hiding a Class During Import
- 3. Packages in Scala
- 3.1. Simple Package
- 3.2. Multiple Packages in the Same File
- 3.3. Package Stacking
- 4. Package Objects
- 5. Conclusion
- Using Scala class defined in package object from Java
- 2 Answers 2
- Пакеты и Импорт
- Создание пакета
- Импорт
- Contributors to this page:
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
import Emp._ object Emp extends Employee
It should be class Emp extends Employee . An companion object in Scala is somewhat different than a class!
1 Answer 1
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.
Packaging, Importing and Package Objects in Scala
In this tutorial, we’ll discuss the concepts of packaging, importing, and package objects in Scala.
We’ll see different ways of importing types, packaging concepts, and some powerful packaging features.
2. Importing in Scala
Import statements bring the required classes and types into the scope of this file. In this section, we will explore different ways to import classes.
2.1. Basic Import
Importing a single class is pretty straightforward and similar to other object-oriented languages such as Java:
import com.baeldung.scala.packageimport.vehicle.Bicycle
In case we want to import every class in a package, we can use the “_” notation:
import com.baeldung.scala.packageimport.vehicle._
We can also specify the classes we want to import in a single line:
import com.baeldung.scala.packageimport.vehicle.
2.2. Aliasing Imports
Sometimes there are cases where we have to import modules with the same name from different packages:
import java.util.Date import java.sql.Date
In this case, we have different date classes that return different date formats. java.sql.Date displays the date without time information whereas java.util.Date displays date and time information.
In order to avoid namespace collisions or confusion, we need to set aliasing of classes in the import statements:
import java.util. utilDate> import java.sql. sqlDate>
Our aliases are now usable as any other object name:
Let’s see an example of what our class could output:
I am a vehicle running on Wed May 27 13:50:53 CEST 2020 ! I am a vehicle running on 2020-05-27 !
2.3. Hiding a Class During Import
During import, we can hide a particular class from a package while importing all other classes of the same package. Let’s look at how we can hide only the java.util.Date class from java.util package:
import java.util. _, _> import java.sql.Date
Now we can create a date object without worrying about any collisions:
3. Packages in Scala
Scala provides multiple ways to define packages. Let’s look at them in this section.
3.1. Simple Package
We can create Scala packages in the same way as we do in Java. We have to declare the package name at the top of the class:
package com.baeldung.scala package object packageimport < trait Motor < val dieselMessage: String = "I am not environment friendly" val noDieselMessage: String = "I am environment friendly" >>
3.2. Multiple Packages in the Same File
We can place multiple packages in one file using curly braces. In this case, we can have two classes with similar names in different packages:
package com.baeldung.scala.packageimport.vehicle < import java.util.utilDate> import java.sql. sqlDate> abstract class Vehicle(numberOfTires: Int, brand: String) < def run(): Unit = < val dt: utilDate = new utilDate() val dtSql: sqlDate = new sqlDate(System.currentTimeMillis()) println(s"I am a vehicle running on $dt !") println(s"I am a vehicle running on $dtSql !") >> > package com.baeldung.scala.packageimport.vehicleNew < import java.sql.sqlDate> abstract class Vehicle(numberOfTires: Int, brand: String) < def run(): Unit = < val dtSql: sqlDate = new sqlDate(System.currentTimeMillis()) println(s"I am a NEW vehicle running on $dtSql !") >> >
We can refer to the first type as com.baeldung.scala.packageimport.vehicle.Vehicle and the second type as com.baeldung.scala.packageimport.vehicleNew.Vehicle.
3.3. Package Stacking
We can write multiple package statements at the top of the class and stack them together. This is similar to writing nested package statements. Let’s look at an example:
package com.baeldung.scala package packageimport package stacking
The above package statements are equivalent to package com.baeldung.scala.packageimport.stacking. However, the difference is that now we can access any classes from each of the stacked packages without additional import statements.
This avoids the need to use import com.baeldung.scala._ to import all the classes from that package. Similarly, we can access the classes from the package com.baeldung.scala.packageimport without any additional import statements.
4. Package Objects
Package objects allow us to keep methods, functions, and variables directly aligned with a package. As a result, all the child members of this package would be able to access them.
For each package, we are only allowed to create one package object where we put the source code for the package in. According to the Scala convention, we should always call it package.scala. Let’s create a package object for the package packageimport and keep the content in package.scala file:
package com.baeldung.scala package object packageimport < val year = "2020" trait Motor < val dieselMessage: String = "I am not environment friendly" val noDieselMessage: String = "I am environment friendly" >>
All members of com.baeldung.scala.packageimport will be able to access year and Motor. In addition, we won’t have to import package object in any of those members:
object bmwB38 extends Motor
5. Conclusion
In this article we looked at how we can use import, package other components, and how to use package objects.
We saw different ways to import packages, how to hide classes from import, and how to deal with importing classes that have the same name. Furthermore, we discussed different approaches to packaging.
Finally, we explored the powerful feature of package objects, which help us to encapsulate methods, variables, and other components at the top level.
As always, the code can be found over on GitHub.
Using Scala class defined in package object from Java
The problem arises when trying to use the MyTest class from Java. I think that since package$MyTest contains a $ in the name, Java is not acknowledging its existence. Nevertheless, the package$ class is accessible. Running javap on package$MyTest.class returns:
Compiled from "Test.scala" public class com.mycompany.test.package$MyTest
I’ve tried accessing the class using Eclipse, Intellij and Netbeans, without success. Is it possible to use Scala classes defined in package objects from Java?
2 Answers 2
Defining a class inside the package object test is currently not implemented the same way as defining it inside the package test , although it probably should (this is being tracked as SI-4344).
Because of that, it is usually good practice to place into the package object only definitions that cannot be top level, like vals, defs, etc. (this is the whole point of package objects after all), and leave class/object definitions into a normal package definition:
package com.mycompany package object test < // vals, defs, vars, etc. val foobar = 42 >package test < // classes, objects, traits, etc. class MyTest < def foo(): Int = < 42 >> >
This will produce a normal MyTest class, easily accessible from Java:
com/mycompany/test/MyTest.class com/mycompany/test/package.class com/mycompany/test/package$.class
Пакеты и Импорт
Scala использует пакеты для указания пространства имен, они позволяют создавать модульную структуру кода.
Создание пакета
Пакеты создаются путем объявления одного или нескольких имен пакетов в верхней части файла Scala.
По соглашению пакеты называют тем же именем, что и каталог, содержащий файл Scala. Однако Scala не обращает внимания на расположение файлов. Структура каталогов sbt-проекта для package users может выглядеть следующим образом:
- ExampleProject - build.sbt - project - src - main - scala - users User.scala UserProfile.scala UserPreferences.scala - test
Обратите внимание, что каталог users находится внутри каталога scala и как в пакете содержатся несколько файлов Scala. Каждый файл Scala в пакете может иметь одно и то же объявление пакета. Другой способ объявления пакетов — с помощью фигурных скобок:
package users < package administrators < class NormalUser >package normalusers < class NormalUser >>
Как видите, такой способ позволяет вкладывать пакеты друг в друга, а также обеспечивает отличный контроль за областью видимости и возможностью изоляции.
Имя пакета должно быть все в нижнем регистре, и если код разрабатывается в организации имеющей сайт, то следует использовать имя следующего формата: .. . Например, если бы у Google был проект под названием SelfDrivingCar , название пакета выглядело бы следующим образом:
package com.google.selfdrivingcar.camera class Lens
Что может соответствовать следующей структуре каталога: SelfDrivingCar/src/main/scala/com/google/selfdrivingcar/camera/Lens.scala .
Импорт
Указание import открывает доступ к членам (классам, трейтам, функциям и т.д.) в других пакетах. Указание import не требуется для доступа к членам одного и того же пакета. Указание import избирательны:
import users._ // групповой импорт всего пакета users import users.User // импортировать только User import users. // импортировать только User, UserPreferences import users. UPrefs> // импортировать и переименовать
Одним из отличий Scala от Java является то, что импорт можно использовать где угодно:
def sqrtplus1(x: Int) = import scala.math.sqrt sqrt(x) + 1.0 >
В случае возникновения конфликта имен и необходимости импортировать что-либо из корня проекта, имя пакета должно начинаться с префикса _root_ :
package accounts import _root_.users._
Примечание: Пакеты scala и java.lang , а также object Predef импортируются по умолчанию.
Contributors to this page:
Contents
- Введение
- Основы
- Единобразие типов
- Классы
- Значения Параметров По умолчанию
- Именованные Аргументы
- Трейты
- Кортежи
- Композиция классов с трейтами
- Функции Высшего Порядка
- Вложенные Методы
- Множественные списки параметров (Каррирование)
- Классы Образцы
- Сопоставление с примером
- Объекты Одиночки
- Регулярные Выражения
- Объект Экстрактор
- Сложные for-выражения
- Обобщенные Классы
- Вариантность
- Верхнее Ограничение Типа
- Нижнее Ограничение Типа
- Внутренние классы
- Члены Абстрактного Типа
- Составные Типы
- Самоописываемые типы
- Неявные Параметры
- Неявные Преобразования
- Полиморфные методы
- Выведение Типа
- Операторы
- Вызов по имени
- Аннотации
- Пакеты и Импорт
- Объекты Пакета
- English
- Bosanski
- Español
- Français
- 한국어
- Português (Brasil)
- Polski
- 中文 (简体)
- ภาษาไทย
- Русский
- 日本語