(12) Organize Classes

(12) Organize Classes

About

:octocat: GitHub: All of the example code: repo (link)

:page_facing_up: blog link: https://purrgramming.life/cs/programming/fp/ :star:


Package

Intro

Classes and objects are organized in packages.

To place a class or object inside a package, use a package clause at the top of your source file.

package progfun.examples 
object Hello 
...

This would place Hello in the package progfun.examples.
You can then refer to it by its fully qualified name, progfun.examples.Hello. For instance, to run the Hello program:

> scala progfun.examples.Hello

file

Example

package my
package pkg.hierarchy

object  Data{
    val course: "Functional Programming Principles"
}

What is the fully qualified name of ‘course’?

'my.pkg.hierarchy.Data.course'

‘Data’ contains ‘course’ and is defined in the ‘my.pkg.hierarchy’ package.

Import

Intro

You can import from either a package or an object.

Say we have a class Rational in package week3. You can use the class using its fully qualified name:

val r = week3.Rational(1, 2) 

Alternatively, you can use an import:

import week3.Rational val r = Rational(1, 2)

Forms of Imports

Imports come in several forms:

Named imports

import week3.Rational // imports just Rational 
import week3.{Rational, Hello} // imports both Rational and Hello 

Wildcard import

import week3._ // imports everything in package week3

Some entities are automatically imported into any Scala program.
These are:

  • All members of package scala
  • All members of package java.lang
  • All members of the singleton object scala.Predef.

Here are the fully qualified names

$$
\begin{array}{ll}
\text { Int } & \text { scala. Int } \
\text { Boolean } & \text { scala. Boolean } \
\text { Object } & \text { java.lang. Object } \
\text { require } & \text { scala. Predef.require } \
\text { assert } & \text { scala. Predef. assert }
\end{array}
$$

Scala’s Class Hierarchy

Any:

  • The base type of all types
  • Methods: ==, equals, hashCode, toString.

AnyRef:

  • The base type of all reference types;
  • Alias of java.lang.Object

AnyVal:

  • The base type of all primitive types.

Nothing:

  • It is a subtype of every other type.
  • There is no value of type Nothing
  • To signal abnormal termination
  • As an element type of empty collections

Type Hierarchies in Scala | Baeldung on Scala

Example

The type of

if true then 1 else false

is AnyVal

 val res0: AnyVal = 1  

Leave a Reply

Your email address will not be published. Required fields are marked *