My Second Blog Post

Author

Noelia Paz

Published

December 1, 2023

My Second Blog Post

Let’s learn about class and object! Did you know that Scala focuses on object oriented programming? It is unique to its language, and that’s what it focuses on:

The class is the instruction, and the object is the thing you build based on those instructions.

A recipe (class) to make cookies (Objects).

Let’s go over functional and imperative programming!

Functional:

  • code is written in such a way that existing variables are not modified while the program is running.
  • Values are specified as function parameters, and output is generated based on their parameters.
  • Functions are required to return the same output when specifying the same parameters on each call.

Imperative:

  • It’s normal to have mutable variables and classes that keep internal states

  • This can lead to both subtle and hard-to-find bugs, especially where multiple threads try to alter a variable at the same time.

  • Used in Java! [standard POJO has variables that can be freely changed by calling the setter methods]

Now, traditional object oriented programming in Scala!

  • First, define the class

  • Then, add variables

  • Then, add the operations you need to perform.

  • Add the method

  • Then print the output passing arguments to it

  • To let the add method return different values, different parameters will have to be passed to the add method.

  • Functional programming is a popular choice for programs that use multiple threads.

  • Methods cannot alter the state of data structures that are used in multiple threads, it’s often much more safe than using imperative code.

  • Requires a different mindset from the developer

Scala Syntax and Rules

  • statically typed language, you have to declare variables before you use them.

  • A mutable variable has been declared:

  • It can be used to store instances of the same type or types

  • Or can be upcast to that type

Upcasting: moving from child to parent type

Java.lang.object: common object used in java, and under ‘Any’ type in Scala.

  • Able to line for variable j. -A string type can be upcast to java.lang.Object
  • The j variable will happily store a reference to the hello world string.

What Cannot Happen - Giving a string type to the i variable from up above - Strings cannot be upcasted to an Int instance

Mutuable and Immutable Variables

Classes

Any is Scala’s parent class

Subclasses

AnyRef:

  • used by reverence variable

  • methods; equals, hashcode, finalize

AnyVal:

  • used by value classes

  • cannpt create primitive values

Primitive values: These wrapper classes are subclasses of the AnyVal class.

Scala wrapper: subclasses implement all the binary operators that you use for calculations