Scala packages are similar to Java packages with few differences.
In Scala,
a. a single source file have contributions to multiple packages.
b. No relationship between packages and source directories.
Step 1: Create new Scala project ‘packages-demo’ in Eclipse.
Step 2: Create new scala package object ‘com.sample.app.model’.
Define new Scala class Employee.scala in the package ‘com.sample.app.model’.
Employee.scala
package com.sample.app.model
class Employee(id: Int, firstName: String, lastName: String) {
override def toString = s"$id : ($firstName, $lastName)"
}
Step 3: Define Scala App class MainApp in the package ‘com.sample.app’.
MainApp.scala
package com.sample.app
import com.sample.app.model.Employee
object MainApp extends App {
val emp1 = new Employee(1, "Ram", "Gurram")
println(emp1)
}
Total project structure looks like below.
Run MainApp.scala, file, you will see below messages in console.
1 : (Ram, Gurram)
import com.sample.app.model.Employee
To use Employee class in current Scala application, you should import it.
How to import all the classes of a package?
Use package._ to import all the types of package.
Example
import com.sample.app.model._
How static imports work?
It is similar to normal imports.
import java.util.Math._
Above statement imports all the static methods of Math class.
You can download complete application from below link.
https://github.com/harikrishna553/scala-examples/tree/master/packages-demo
Single source file have contributions to multiple packages.
In Scala, you can define types that belongs to multiple packages in same source file.
AppModels.scala
package com.sample.app
package com {
package sample {
package app {
package dao {
class User(id: Int, name: String) {
override def toString = s"$id : ($name)"
}
}
package dto {
class UserDto(id: Int, name: String) {
override def toString = s"$id : ($name)"
}
}
}
}
}
MainApp.scala
package com.sample.app
import com.sample.app.dao.User
import com.sample.app.dto.UserDto
object MainApp extends App {
val user1 = new User(1, "Ram")
val userDto1 = new UserDto(1, "Ram")
println(user1)
println(userDto1)
}
Run MainApp.scala file, you will see below messages in console.
1 : (Ram)
1 : (Ram)
https://github.com/harikrishna553/scala-examples/tree/master/nested-packages
Note
a. How to import more than one class of a package?
Import java.util.{List, Map}
If you are comfortable with multi line imports you can use this.
Import java.util.List
Import java.util.Map
b. Create alias of a class
import java.util.{ArrayList => MyArrayList}
Aliases are used to resolve name conflicts of types.
c. Import everything from a package except this type
import java.util.{ArrayList => _, _}
Above statement import all the types except ArrayList.
d. imports can be used anywhere, not necessarily at top of the file.
package com.sample.app
object MainApp extends App {
import java.util.Arrays
var myList = Arrays.asList(2, 3, 5)
myList.forEach(println)
}
Previous Next Home
No comments:
Post a Comment