YouTube Icon

Interview Questions.

Top 50 Scala Interview Questions - Jul 28, 2022

fluid

Top 50 Scala Interview Questions

Q1. What Is Apply Method In Scala? What Is Unapply Method In Scala? What Is The Difference Between Apply And Unapply Methods In Scala?

In Scala, observe and unapply strategies play very critical function. They also are very beneficial in Play Framework in mapping and unmapping information among Form statistics and Model statistics.

In easy words,

follow method: To compose or assemble an object from it’s components.

Unapply method: To decompose or dis-collect an item into it’s components.

Scala’s follow approach: It is used to compose an item by the use of its components. Suppose if we want to create a Person object, then use firstName and laststName  additives and compose Person object as proven under.

Class Person(val firstName: String, val lastName: String)

item Person

  def apply(firstName: String, lastName: String) 

        = new Person(firstName, lastName)

 

Scala’s unapply approach:

It is used to decompose an item into its components. It follows opposite process of follow approach. Suppose if we've a Person item, then we can decompose this object into it’s two additives: firstName and laststName as shown underneath.

Magnificence Person(val firstName: String, val lastName: String)

item Person

  def apply(firstName: String, lastName: String) 

        = new Person(firstName, lastName)

 

    def unapply(p: Person): (String,String) 

        = (p.FirstName, p.LastName)

 

Q2. What Is The Use Of Auxiliary Constructors In Scala?Please Explain The Rules To Follow In Defining Auxiliary Constructors In Scala?

In Scala, The foremost purpose of Auxiliary Constructors is to overload constructors. Like Java, We can provide numerous kinds of constructors in order that use can select the right one based on his requirement.

Auxiliary Constructor Rules:

They are like techniques only. Like methods, we must use ‘def’ key-word to outline them.

We need to use same call ‘this’ for all Auxiliary Constructors.

Each Auxiliary Constructor have to begin with a name to previous defined every other Auxiliary Constructor or Primary Constructor. Otherwise collect-time mistakes.

Each Auxiliary Constructor must differ with their parameters list: can be via wide variety or types.

Auxiliary Constructors can not name a extraordinary class constructors. They need to call them via Primary Constructor simplest.

All Auxiliary Constructors call their Primary Constructor either immediately or not directly through different Auxiliary Constructors.

NOTE:- If you want to study Scala’s Constructors, please refer my Scala posts at: Primary Constructor and Auxiliary Constructor.

Q3. How To Implement Interfaces In Scala?

As we understand from Java background, we use interface to outline contact.

However, there's no interface idea in Scala. Even, Scala doesn’t have interface keyword. Scala has a greater effective and bendy idea i.E. Trait for this motive.

Q4. What Is Call-through-name? Does Scala And Java Support Call-by-call? What Is The Difference Between Call-by using-price And Call-by way of-name Function Parameters?

Call-via-name means evaluates technique/characteristic parameters only when we need them or we get entry to them. If we don’t use them, then it does no longer evaluate them.

Scala supports both name-by means of-price and speak to-via-call feature parameters. However, Java helps simplest name-by using-price, but not call-via-call.

Difference among name-by way of-cost and make contact with-by using-name:

The main difference among these two are defined underneath:

In Call-by means of-name, the function parameters are evaluated best each time they're wanted but no longer while the function is called.

In Call-by means of-value, the function parameters are evaluated whilst the characteristic is known as.

In Call-by way of-price, the parameters are evaluated before executing characteristic and they are evaluated most effective as soon as regardless of how commonly we used them in that feature.

In Call-by-call, the parameters are evaluated on every occasion we get right of entry to them and they're evaluated every time we use them in that feature.

Scala Syntax Differences

Call-with the aid of-fee:

1 def myFunction(a: Int, b: Int)  

Here both a and b are Call-through-fee parameters to myFunction.

Call-through-call:

1 def myFunction(a: Int, b: => Int)  

Here each a is a Call-by way of-price parameter and b is Call-by-call to myFunction.

Q5. What Are The Advantages Of Play/scala Stack To Develop Web Applications?

The following are the primary benefits of Play/Scala stack to expand internet packages:

Open Source: Play is an Open-source loose-software framework to increase net applications.

Better Productivity: Play framework’s Auto-reload characteristic improves Developer Productivity. No need to build, install and test our adjustments. Just do our adjustments and refresh the web page to peer our modifications.

Stateless and Easy to Develop REST API: Play is HTTP based stateless model to serve web requests so it's miles very easy to increase REST API or RESTful Web Services.

Better Error-Handling: If we expand our web utility the usage of Play framework,it informs all mistakes inside the browser in very beneficial format. It shows errors message, the record region, line range in which blunders occurred, highlighting the code-snippet to understand the error very without problems.

High Performance and Better Scalability With Reactive: Play framework is evolved by following Reactive design styles and it is built on pinnacle of Netty sever to make use of Non-blocking off IO Feature. Because of this feature, we can expand very fairly Scalable and performance applications very easily.

Easy to Extend: Play may be very bendy framework and supports developing plug-ins very smooth to increase it’s features and capability.

Highly Concurrency and Better Parallelism: As both Scala and Play helps Functional Programming, it's far very smooth to broaden Highly Concurrency and Better Parallelism packages very easily due to the fact FP supports Immutability, Pure Functions (Functions without side-outcomes), Pattern Matching, Actor Model and many others.

Better Reusability, Easy to Test and More Modular: As each Scala and Play helps Functional Programming, we are able to develop more modular and reusable applications. It is also very easy to test greater modular programs.

Q6. What Are The Four Types Of Scala Identifiers ?

The 4 forms of identifiers are

Alpha numeric identifiers

Operator identifiers

Mixed identifiers

Literal identifiers

Q7. What Is The Current Latest Version Of Scala? What Is The Major Change Or Update In Scala 2.12?

Current Scala’s solid is 2.Eleven.@It helps Java SE 7.

The predominant change or replace in Scala 2.12 model is that it helps Java SE eight or later variations most effective. Scala 2.12 isn't a binary well matched with the two.11.X collection. It’s still in Mile Stone Builds most effective.

Q8. If I Want To Become A Fullstack Scala Developer, Which Technology Stack I Should Learn?

If you need to end up a Fullstack Scala Developer, you must study the subsequent era stack:

Scala 2.Eleven.7

Play 2.Four.6 Framework

Akka 2.Three Framework

One Build Tool: SBT/Maven

One JS Framework: CoffeeScript/JavaScript

One IDE: IntelliJ IDEA 15/ Eclipse IDE 4.X

One TDD & BDD Framework: ScalaTest,Spec2,ScalaCheck,Mockito

Micro Services with Play and Scala

SCoverage

Scalastyle

Functional Programming Design Patterns

Machine Learning with Scala

Q9. What Is Option In Scala? What Are Some And None? What Is Option/some/none Design Pattern In Scala?

In Scala, Option is used to symbolize optionally available values this is both exist or no longer exist.

Option is an abstract class. Option has  subclasses: Some and None. All three (Option, Some and None) are described in “scala” package deal like “scala.Option”.

Option is a bounded series in Scala, which incorporates either 0 or one detail. If Option contains zero elements this is None. If Option contains one element, this is Some.

Some is used to represent current value. None is used to represent non-existent price.

Example:-

def get(val index: Int): Option[String]

Let us assume that this approach is from List. This approach has a return form of Option[String]. If List consists of factors, this get approach returns “Some[String]” element to be had in that index function. Otherwise, it returns “None” (that is no factors)

Some is a case elegance and None is an Object. As each are case class/object, we are able to use them in Pattern Matching very well.

The combination of these types of 3 definitions is referred to as Option/Some/None Design Pattern in Scala.

Q10. What Is Scala Anonymous Function?

In a source code, nameless functions are known as ‘function literals’ and at run time, function literals are instantiated into items called characteristic values.  Scala affords a enormously clean syntax for outlining anonymous features.

Q11. How Do I Append To The List?

In scala to append into a list, use “:+” unmarried fee

       var myList = List.Empty[String]

       myList :+= "a"

       myList :+= "b"

       myList :+= "c"

       use++ for appending a listing

       var myList = List.Empty[String]

       myList ++= List("a", "b", "c")

Q12. What Are The Available Build Tools To Develop Play And Scala Based Applications?

The following three are most famous to be had Build Tools to broaden Play and Scala Applications:

SBT

Maven

Gradle

Q13. What Is Either In Scala? What Are Left And Right In Scala? Explain Either/left/proper Design Pattern In Scala?

In Scala, Either is an summary magnificence. It is used to represent one cost of  possible types. It takes  type parameters: Either[A,B].

It precisely have two subtypes: Left and Right. If Either[A,B] represents an example A which means it is Left. If it represents an instance B which means it is Right.

This is known as Either/Left/Right Design Pattern in Scala.

Q14. Explain What Is Scala?

Scala is an item purposeful programming and scripting language for popular software program applications designed to express solutions in a concise manner.

Q15. What Are The Advantages Of Functional Programming (fp) Or Advantages Of Pure Functions?

The following are the Advantages of Functional Programming (FP) or Advantages of Pure Functions:

More Modular

Easier to apprehend Or Easier cause about

Easier to test

Less vulnerable to insects

Easier to reuse

Easier to Parallelism and generalize

Q16. When Compare To Normal Class, What Are The Major Advantages Or Benefits Of A Case-class?

The following are the important blessings or benefits of a Case elegance over Normal Classes:

Avoids plenty of boiler-plate code by including a few useful techniques mechanically.

By default, helps Immutability as it’s parameters are ‘val’

Easy to apply in Pattern Matching.

No want to use ‘new’ key-word to create example of Case Class.

By default, helps Serialization and Deserialization.

Q17. What Is Case Class? What Is Case Object? What Are The Advantages Of Case Class?

Case elegance is a class that's defined with “case elegance” key phrases. Case object is an item which is defined with “case item” key phrases. Because of this “case” key-word, we will get some advantages to avoid boilerplate code.

We can create case class items with out using “new” keyword. By default, Scala compiler prefixes “val” for all constructor parameters. That’s why with out using val or var, Case class’s constructor parameters becomes class members, it is not viable for ordinary instructions.

Advantages of case magnificence:

By default, Scala Compiler provides toString, hashCode and equals strategies. We can keep away from scripting this boilerplate code.

By default, Scala Compiler adds associate object with follow and unapply methods that’s why we don’t need new key-word to create times of a case magnificence.

By default, Scala Compiler provides copy approach too.

We can use case instructions in Pattern Matching.

By default, Case class and Case Objects are Serializable.

Q18. What Is Monad In Scala?

A monad is an object that wraps every other object. You skip the Monad mini-programs, i.E features, to perform the facts manipulation of the underlying item, in preference to manipulating the object immediately.  Monad chooses the way to observe the program to the underlying item.

Q19. What Are The Popular Scala-primarily based Frameworks To Develop Restful Web Services Or Rest Api?

There are many Scala-Based Framework to expand RESTful Web Services. Most popular frameworks are:

Play Framework: n Play, we call REST API URLs as routes. We place all routes at once place in Play framework. It is a stateless internet framework to increase REST API without problems.

Scalatra Framework: It is quite simple and easy Scala-based internet framework to expand REST API

Spray Framework: It could be very concise and built on pinnacle of Akka framework so it’s higher to expand REST API using Actor Model.

Lift Framework: It permits routing the usage of Pattern Matching idea.

Q20. What Is The Difference Between Var And Value?

In scala, you could define a variable the use of either a, val or var keywords.  The distinction between val and var is,  var is similar to java declaration, however val is little distinct.  We can't trade the reference to factor to any other reference, once the variable is said using val. The variable described the use of var keywords are mutable and may be modified any variety of instances.

Q21. What Is The Use Of Tuples In Scala?

Scala tuples integrate a fixed variety of objects together in order that they can be handed round as entire. A tuple is immutable and might hold items with differing types, in contrast to an array or listing.

Q22. How Many Values Of Type Nothing Have In Scala?

In Scala, Nothing kind have no values that is zero. It does not have any values. It is a subtype of all Value training and Reference training.

Q23. Explain The Main Difference Between List And Stream In Scala Collection Api? How Do We Prove That Difference? When Do We Choose Stream?

In Scala, both List and Stream are from Collection API and works almost similar. Both are Immutable collections.

However, there's one main distinction between List and Stream in Scala Collection API: That is List elements are evaluated Eagerly and Stream factors are evaluated Lazily meaning when we get entry to them.

Scala> var list1 = List(1,2,three,four)

list1: List[Int] = List(1, 2, 3, 4)

Here we can take a look at that all List factors evaluated on the time of creating List item. However, if we do identical element on Stream, we can not see all elements. We can see most effective first evaluated element and last elements are evaluated lazily as proven under:

scala> var s1 = Stream(1,2,three,four)

s1: scala.Series.Immutable.Stream[Int] = Stream(1, ?)

When we need Lazy series to assess elements most effective when we get right of entry to them then it’s higher to apply Stream.

Q24. What Is Recursion Tail In Scala?

‘Recursion’ is a function that calls itself. A characteristic that calls itself, as an instance, a function ‘A’ calls feature ‘B’, which calls the feature ‘C’.  It is a method used regularly in practical programming.  In order for a tail recursive, the decision returned to the function ought to be the ultimate characteristic to be executed.

Q25. How Do We Declare A Private Primary Constructor In Scala? How Do We Make A Call To A Private Primary Constructor In Scala?

In Scala, we can claim a private Primary Constructor very without difficulty. Just outline a Primary Constructor as it is and upload ‘personal’ just after elegance name and before parameter list as proven beneath:

class Person personal (name: String)

item Person

 def practice(call: String) = new Person(name)

 

As it’s a private constructor, we cannot name it from outside. We ought to provide a manufacturing unit technique (that is practice method) as shown above and use that constructor indirectly.

Q26. Which Ides Support Play And Scala-primarily based Applications Development And How?

The following  famous IDEs guide Play and Scala-Based Applications Development:

IntelliJ IDEA

Eclipse IDE

They aid by way of the usage of Scala Plugins like Eclipse IDE has a Scala IDE for Eclipse to assist Play and Scala-Based Applications Development.

IntelliJ IDEA has a plug-in like “Scala Plugin for IntelliJ IDEA” to aid “Scala, SBT and Play 2 Framework” primarily based applications.

Q27. How Do You Prove That By Default, Case Object Is Serializable And Normal Object Is Not?

Yes, By Default, Case Object is Serializable. But regular object isn't always. We can show this via the usage of isInstanaceOf technique as proven underneath:

scala> item MyNormalObject

defined item MyNormalObject

scala> MyNormalObject.IsInstanceOf[Serializable]

res0: Boolean = fake

scala> case object MyCaseObject

described item MyCaseObject

scala> MyCaseObject.IsInstanceOf[Serializable]

res1: Boolean = authentic

Q28. What Is Diamond Problem? How Scala Solves Diamond Problem?

A Diamond Problem is a Multiple Inheritance trouble. Some people calls this hassle as Deadly Diamond Problem.

In Scala, it occurs when a Class extends a couple of Traits that have same approach definition.

Unlike Java 8, Scala solves this diamond problem mechanically by following a few rules described in Language. Those regulations are called “Class Linearization”.

Example:-

trait A   

  def show() println("From A.Display")  

trait B extends A 

  override def display()  println("From B.Show") 

trait C extends A 

  override def display()  println("From C.Show") 

elegance D extends B with C 

 

item ScalaDiamonProblemTest extends App 

    val d = new D

    d display

 

Here output is “From C.Show” form trait C. Scala Compiler reads “extends B with C” from right to left and takes “display” method definition from lest maximum trait this is C.

Q29. What Is The Best Language To Use With Play Framework: Scala Or Java?

Play 2 is absolutely written in Scala. If we use Java with Play framework, we need to stand many problems because Java does no longer aid complete FP functions.

Scala is the pleasant choice to use with Play framework to broaden Highly Scalable, Better Performance with Concurrency/Parallelism and Low latency programs, due to the fact:

Play 2 is absolutely written in Scala.

It supports complete FP features.

It is more expression language than Java.

It helps Akka Actor model very effortlessly

It supports some new OOP characteristic like Traits.

Play’s built-in templates are advanced in Scala

Q30. When Can You Use Traits?

There isn't any specific rule whilst you may use traits, however there is a guiding principle which you may consider.

If the behaviour will no longer be reused, then make it a concrete magnificence. Anyhow it is not a reusable behaviour.

In order to inherit from it in Java code, an summary magnificence may be used.

If efficiency is a concern then lean toward the use of a category

Make it a trait if it might be reused in multiple and unrelated lessons. In special parts of the class hierarchy most effective tendencies can be combined into different components.

You can use abstract magnificence, if you need to distribute it in compiled shape and expects outdoor corporations to write down instructions inheriting from it.

Q31. What Is The Default Unit And Functional Testing Framework For Play? What Is The Default Build Tool For Play? What Is The Default Template Engine For Play? What Is The Built-in Web Server Available In

Play Framework’s default Unit and Functional Testing Framework is Spec@It could be very clean to test Play/Scala based totally programs the usage of Spec2 Framework.

Play Framework’s Default built-in template is “Twirl”. It became advanced in Scala. By the use of those templates, we will increase Play/Scala primarily based packages very without problems.

The Built-in or Default Web Server available for Play Framework is Netty Server.

Q32. What Are The Scala Variables?

Values and variables are  shapes that come in Scala. A fee variable is regular and can not be modified once assigned.  It is immutable, whilst a regular variable, then again, is mutable, and you may trade the fee.

The two types of variables are

var  myVar : Int=zero;

val   myVal: Int=1;

Q33. What Is An Higher-order Function (hof)?

Higher Order Function (HOF) is also a feature however which plays one, two or each of the subsequent matters:

Take different features as arguments

Return capabilities as their results

Q34. What Are The Popular Mvc Frameworks For Scala Language To Develop Web Applications?

The following are the maximum famous MVC frameworks available for Scala Language to broaden Web Applications:

Play Framework

Scalatra Framework

Spray Framework

Lift Framework

Q35. What Is The Best Code-insurance Tool Available For Play And Scala Based Applications?

SCoverage is the Code-insurance tool for Play and Scala primarily based packages.

SCoverage stands for Scala Code-coverage device. It has three separate plug-ins to helps the subsequent build tools:

SBT

Maven

Gradle

Q36. Popular Clients Who Are Using Play And Scala To Develop Their Applications?

Thousands of customers are the usage of Play and Scala in Production. The following listing is the extra popular clients who are using Play and Scala actively.

LinkedIn

The Guardian

Ocado

LuchidChart

GOV.UK

Q37. Like Hibernate For Java-based Applications, What Are The Popular Orm Frameworks Available To Use In Play/scala Based Applications?

Like JPA, Hibernate and Toplink and many others ORM Frameworks for Java-primarily based applications, There are many ORM frameworks to use in Play/Scala primarily based packages.

Popular ORM frameworks for Play/Scala based programs:

Slick

Anorm

SORM(Scala ORM)

Squeryl

Q38. What Are The Available Unit Testing, Functional Testing And/or Bdd Frameworks For Play And Scala Based Applications?

The following are most famous to be had Unit Testing, Functional Testing and/or BDD Frameworks for Play/Scala Based applications:

Spec2

ScalaTest

ScalaCheck

Mokito

Q39. What Is The Advantage Of Scala?

Less mistakes prone useful fashion

High maintainability and productivity

High scalability

High testability

Provides capabilities of concurrent programming

Q40. Difference Between Array And List In Scala?

Arrays are constantly Mutable in which as List is continually Immutable.

Once created, We can change Array values where as we cannot exchange List Object.

Arrays are constant-size information systems wherein as List is variable-sized records structures. List’s length is mechanically expanded or reduced primarily based on it’s operations we carry out on it.

Arrays are Invariants in which as Lists are Covariants.

Q41. What Are Option, Some And None In Scala?

‘Option’ is a Scala usual type which could either be ‘some’ well-known cost or none.  ‘Queue’ regularly uses it to symbolize primitives that may be null.

Q42. Why Scala Is Better Than Java? What Are The Advantages Of Scala Over Java (java eight)? Compare To Java What Are The Major Advantages Or Benefits Of Scala?

Because Scala helps the following greater functions, it's far better than Java 8:

Full FP Features

More Expression Language

Pattern Matching

Better help for Akka Actor Model

Automatic decision for Inheritance Diamond Problem with Traits

Asynchronous and Non-blockading IO programming using Akka Framework

Fully Reactive Streaming API

Q43. What Is The Best Scala Style Checker Tool Available For Play And Scala Based Applications?

Like Checkstyle for Java-Based Applications, Scalastyle is first-rate Scala fashion checker tool available for Play and Scala based totally programs.

Scalastyle observes our Scala supply code and shows capacity issues with it. It has three separate plug-ins to supports the subsequent build equipment:

SBT

Maven

Gradle

It has  separate plug-ins to helps the subsequent  IDEs:

IntelliJ IDEA

Eclipse IDE

Q44. In Fp, What Is The Difference Between A Function And A Procedure?

Both are used to carry out computation, but they have one most important difference in Functional Programming global.

A characteristic is a computation unit without aspect-effect wherein as a Procedure is likewise a computation unit with facet-outcomes.

Q45. What Is The Difference Between :: And #:: In Scala? What Is The Difference Between ::: And #::: In Scala?

In Scala Collection API,

:: and ::: are techniques available in List class.

#:: and #::: are techniques available in Stream magnificence

In List elegance, :: technique is used to append an detail to the beginning of the list.

Scala> var list1 = List(1,2,three,four)

list1: List[Int] = List(1, 2, three, 4)

 

scala> list1 = zero :: list1

list1: List[Int] = List(zero, 1, 2, 3, 4)

In List magnificence, ::: technique is used to concatenate the factors of a given listing in the front of this listing.

Scala> var list1 = List(3,four,5)

list1: List[Int] = List(3, four, five)

 

scala> val list2 = List(1,2) ::: list1

list2: List[Int] = List(1, 2, 0, 1, 2, 3, 4)

In Stream class, #:: method is used to append a given element at beginning of the move. Only this newly added detail is evaluated and followed by means of lazily evaluated flow factors.

Scala> var s1 = Stream(1,2,three,four)

s1: scala.Series.Immutable.Stream[Int] = Stream(1, ?)

 

scala> s1 = 0 #:: s1

s1: scala.Collection.Immutable.Stream[Int] = Stream(0, ?)

In Stream class, #::: technique is used to concatenate a given circulate at starting of the move. Only this newly delivered element is evaluated and observed by way of lazily evaluated flow elements.

Scala> var s1 = Stream(1,2,3,four)

s1: scala.Series.Immutable.Stream[Int] = Stream(1, ?)

 

scala> val s2 = Stream(-1,0) #::: s1

s2: scala.Collection.Immutable.Stream[Int] = Stream(-1, ?)

:: approach works as a cons operator for List magnificence and #:: method words as a cons operator for Stream class. Here ‘cons’ stands for construct.

::: technique works as a concatenation operator for List elegance and #::: method words as a concatenation operator for Stream elegance.

Q46. Mention The Difference Between An Object And A Class ?

A class is a definition for an outline.  It defines a kind in phrases of techniques and composition of other types.  A elegance is a blueprint of the item. While, an object is a singleton, an example of a class that is specific. An nameless class is created for each object inside the code, it inherits from anything training you declared object to implement.

Q47. What Is Range In Scala? How To Create A Range In Scala?

Range is a Lazy Collection in Scala. Range is a category available in ‘scala’ bundle like ‘scala.Range’. It is used to represent a series of integer values. It is an ordered sequence of integers.

Example:-

scala> 1 to ten

res0: scala.Collection.Immutable.Range.Inclusive = Range(1, 2, 3, four, 5, 6, 7, 8, nine, 10)

scala> 1 until 10

res1: scala.Collection.Immutable.Range = Range(1, 2, 3, 4, five, 6, 7, 8, 9)

Q48. How Scala Solves Inheritance Diamond Problem Automatically And Easily Than Java 8?

If we use Java eight’s Interface with Default techniques, we can get Inheritance Diamond Problem. Developer has to resolve it manually in Java @It does now not offer default or automatic resolution for this hassle.

In Scala, we are able to get same trouble with Traits however Scala is very clever and solves Inheritance Diamond Problem mechanically the usage of Class Linearization concept.

Q49. What Is An Anonymous Function In Scala? What Is A Function Literal In Scala? What Are The Advantages Of A Anonymous Function/feature Literal In Scala?

Anonymous Function is also a Function but it does not have any feature name. It is also called a Function Literal.

The advantages of a Anonymous Function/Function Literal in Scala:

We can assign a Function Literal to variable

We can bypass a Function Literal to every other function/approach

We can return a Function Literal as every other characteristic/technique end result/return cost.

Q50. How To Define Factory Methods Using Object Keyword In Scala? What Is The Use Of Defining Factory Methods In Object?

In Scala, we use ‘object’ keyword to outline Factory strategies. The predominant cause of these Factory methods in Scala is to keep away from the use of ‘new’ key-word. Without using ‘new’ key-word we are able to create objects.

To define Factory strategies:

We can use apply approach to define Factory methods in Scala. If we've got Primary Constructor and Multiple Auxiliary constructors, then we want to define a couple of follow methods as proven below.

Elegance Person(val firstName: String, val middleName: String, val lastName: String)

  def this(firstName: String, lastName: String)

    this(firstName,"",lastName)

  

item Person

  def follow(val firstName: String, val middleName: String, val lastName: String) 

        = new Person(firstName,middleName,lastName)

 

  def practice(val firstName: String, val lastName: String) 

        = new Person(firstName, lastName)

Now we can create Person gadgets without the usage of new key-word or with new keyword upto your wish.

Val p1 = new Person("Scala","Java")

or 

val p1 = Person("Scala","Java")




CFG