Scala Primary Constructor In-Depth - JournalDev [PDF]

Nov 26, 2015 - In this post, we are going to discuss about Scala Primary Constructor in depth with real-time scenario ex

4 downloads 17 Views 536KB Size

Recommend Stories


Manualul inginerului constructor pdf
Courage doesn't always roar. Sometimes courage is the quiet voice at the end of the day saying, "I will

PdF Scala Cookbook
And you? When will you begin that long journey into yourself? Rumi

Scala Sockelleisten Scala Skirts
You often feel tired, not because you've done too much, but because you've done too little of what sparks

Code Cube Constructor
So many books, so little time. Frank Zappa

InDepth Distributed Caching with Memcached
Kindness, like a boomerang, always returns. Unknown

Beaufort Scala
Come let us be friends for once. Let us make life easy on us. Let us be loved ones and lovers. The earth

scala beaufort del vento
You're not going to master the rest of your life in one day. Just relax. Master the day. Than just keep

Teatro alla Scala
Courage doesn't always roar. Sometimes courage is the quiet voice at the end of the day saying, "I will

PDF Scala for the Impatient (2nd Edition)
Your task is not to seek for love, but merely to seek and find all the barriers within yourself that

Focal Scala Utopia
When you do things from your soul, you feel a river moving in you, a joy. Rumi

Idea Transcript


{St Patrick's Day - 6 Hours Flash Sale} - All Udemy Courses at $10.99 Only Ad

Check It Now!

Behavioral Health Analytic Software For Medical Professionals AnalyticsRX

JAVA TUTORIAL

#INDEX POSTS

#INTERVIEW QUESTIONS

RESOURCES

HIRE ME

GET QUOTE

DOWNLOAD ANDROID APP

CONTRIBUTE

HOME » SCALA » SCALA PRIMARY CONSTRUCTOR IN-DEPTH

Scala Primary Constructor In-Depth NOVEMBER 26, 2015 BY RAMBABU POSA — 5 COMMENTS

In this post, we are going to discuss about Scala Primary Constructor in depth with real-time scenario examples.

Table of Contents [hide] 1 Post Brief TOC 2 Introduction 3 Primary Constructor in Scala 4 Scala val and var in-brief 5 Scala Primary Constructor With val and var 6 Scala Primary Constructor in-brief

Post Brief TOC Introduction Primary Constructor in Scala Scala val and var in-brief Scala Primary Constructor With val and var Scala Primary Constructor in-brief

Introduction As we know, Constructor is used to create instances of a class. Scala supports constructors in different way than in Java. In Scala Language, a class can have two types of constructors:

Primary Constructor Auxiliary Constructor A Scala class can contain only Primary Constructor or both Primary Constructor and Auxiliary Constructors. A Scala class can contain one and only one Primary constructor, but can contain any number of Auxiliary constructors. We will discuss Primary Constructor in-detail in this post and Auxiliary Constructor in-detail in my coming post. Before going to next sections, we need to understand Class Definition and Class Body as shown in the diagram below:

Class Body is defined with two curly braces “{ }”. First line is Class Definition.

Primary Constructor in Scala In Scala, a Primary Constructor is a Constructor which starts at Class definition and spans complete Class body. We can define Primary Constructor with zero or one or more parameters. Now, we will discuss them one by one with some simple examples. Example-1:-Create a Person class with default Primary Constructor.

class Person{ // Class body goes here }

1 2 3

Here we have defined No-Argument or Zero-Arguments constructor like “Person()”. It is also known as “Default Constructor” in Java. We can create an instance of Person class as shown below: 1 2 3

val p1 = new Person() var p2 = new Person

Both are valid in Scala. We can use No-Arguments constructor without parenthesis. Example-2:Primary Constructor’s parameters are declared after the class name as shown below: class Person(firstName:String, middleName:String, lastName:String){ // Class body goes here }

1 2 3

Here Person class’s Primary Constructor has three parameters: firstName, middleName and lastName. Now, We can create an instance of Person class as shown below: 1

val p1 = new Person("First","","Last")

If we observe this example, some People may have Middle Name or not but still they have to provide all 3 parameters. It is not efficient way to deal with constructors in Scala. We can use Auxiliary Constructors to solve this problem (Please go through my next post). Example-3:Anything we place within the Class Body other than Method definitions, is a part of the Primary Constructor. class Person(firstName:String, middleName:String, lastName:String){ println("Statement 1") def fullName() = firstName + middleName + lastName println("Statement 2") }

1 2 3 4 5 6 7

When we execute above program in Scala REPL, we can get the following output: 1 2 3 4

scala> var p1 = new Person("Ram","","Posa") Statement 1 Statement 2 p1: Person = Person@3eb81efb

If we observe that output, as both println statements are defined in Class Body, they become the part of Primary Constructor. Example-4:-:Any Statements or Loops (like If..else, While,For etc) defined in the Class Body also become part of the Primary Constructor. class Person(firstName:String, middleName:String, lastName:String){ def fullName() = firstName + middleName + lastName if (middleName.trim.length ==0) println("Middle Name is empty.") }

1 2 3 4 5 6 7

Output:1 2 3

scala> var p1 = new Person("Ram","","Posa") Middle Name is empty. p1: Person = Person@64a40280

Example-5:-:Not only Statements or Expressions, any method calls defined in the Class Body also become part of the Primary Constructor. class Person(firstName:String, middleName:String, lastName:String){ def fullName() = firstName + middleName + lastName fullName // A No-argument Method Call }

1 2 3 4 5 6

Output:1 2 3

scala> var p1 = new Person("Ram","-","Posa") Ram-Posa p1: Person = Person@64a40280

Scala val and var in-brief Before discussing about Scala Primary Constructor, we need to revisit about Scala Field definitions concept. In Scala, “val” and “var” are used to define class fields, constructor parameters, function parameters etc. “val” means value that is constant. “val” is used to define Immutable Fields or variables or attributes. Immutable fields means once we create we cannot modify them. “var” means variable that is NOT constant. “var” is used to define Mutable Fields or variables or attributes. Mutable fields means once we create, we can modify them.

Scala Primary Constructor With val and var In Scala, we can use val and var to define Primary Constructor parameters. We will discuss each and every scenario with simple examples and also observe some Scala Internals. We have defined three different Scala sources files as shown below:

Example-1:In Scala, if we use “var” to define Primary Constructor’s parameters, then Scala compiler will generate setter and getter methods for them. Person1.scala class Person1(var firstName:String, var middleName:String, var lastName:String)

1 2 3

Open command prompt at Source Files available folder and compile “Person1.scala” as shown below:

This step creates “Person1.class” file at same folder. “javap” command is the Java Class File Disassembler. Use this command to disassemble “Person1.class” to view its content as shown below:

As per this output, we can say that “var” is used to generate setter and getter for constructor parameters. As per Scala Notation, setter and getter methods for firstName Parameter: Getter Method public java.lang.String firstName();

1

Setter Method public void firstName_$eq(java.lang.String);

1

This “firstName_$eq” method name is equal to “firstName_=”. When we use “=” in Identifiers Definition(Class Name, Parameter Name, Method names etc.), it will automatically convert into “$eq” Identifier by Scala Compiler. NOTE:Scala does not follow the JavaBeans naming convention for accessor and mutator methods. Example-2:In Scala, if we use “val” to define Primary Constructor’s parameters, then Scala compiler will generate only getter methods for them. Person2.scala class Person1(val firstName:String, val middleName:String, val lastName:String)

1 2 3

Open command prompt, compile and use “javap” to disassemble to see the generated Java Code as shown below:

If we observe this output, we can say that “val” is used to generate only getter for constructor parameters. As per Scala Notation, getter methods for firstName, middleName and lastName Parameters: Getter Methods public java.lang.String firstName(); public java.lang.String middleName(); public java.lang.String lastName();

1 2 3

Example-3:In Scala, if we don’t use “var” and “val” to define Primary Constructor’s parameters, then Scala compiler does NOT generate setter and getter methods for them. Person3.scala class Person1(firstName:String, middleName:String, lastName:String)

1 2 3

Open command prompt, compile and use “javap” to disassemble to see the generated Java Code as shown below:

If we observe this output, we can say that no setter and getter methods are generated for firstName, middleName and lastName Constructor Parameters.

Scala Primary Constructor in-brief The Scala Primary Constructor consist of the following things: The constructor parameters declare at Class Definition All Statements and Expressions which are executed in the Class Body Methods which are called in the Class Body Fields which are called in the Class Body In Simple words, anything defined within the Class Body other than Method Declarations is a part of the Scala Primary Constructor. That’s it all about Scala Primary Constructor. We will discuss Scala Auxiliary Constructors in-depth in coming posts. Please drop me a comment if you like my post or have any issues/suggestions.

FILED UNDER: SCALA

About Rambabu Posa Rambabu Posa have 12+ years of RICH experience as Sr Agile Lead Java/Scala/BigData/NoSQL Developer. Apart from Java, he is good at Spring4, Hibernate4, MEAN Stack, RESTful WebServices, NoSQL, BigData Hadoop Stack, Cloud, Scala, Groovy Grails, Play Framework, TDD, BDD,Agile,DevOps and much more. His hobbies are Developing software, Learning new technologies, Love Walking, Reading Books, Watching TV and obviously sharing his knowledge through writing articles on JournalDev.

« JMS API 2.0 Producer and Consumer

The Ultimate Guide of Black Friday Deals »

Comments arun says MAY 25, 2017 AT 11:04 AM

This s excellent, everything about constructors on one page..thanks Reply

Kadimi Balu says APRIL 19, 2017 AT 8:09 AM

Am searching Google for the constructors in Scala and i read so many blogs but this is the best information with simple examples Thanks you Reply

vijay says MARCH 9, 2017 AT 3:20 AM

Example 5 is not working…. class Person(firstName:String, middleName:String, lastName:String){ def fullName() = firstName + middleName + lastName fullName // A No-argument Method Call } OUTPUT :: scala> new Person(“H”,”E”,”MAN”) res0: Person = Person@4e302a4b method call is not called in the primary constructor… I am using 2.10 version… Is it updated in the newer version Reply

kavya says JANUARY 31, 2017 AT 9:28 PM

very well explained Reply

ldp says NOVEMBER 26, 2015 AT 6:59 PM

Great post! It helps me a lot. Now I understand how to write the constructor correctly in scala. Looking forward to your next post! Reply

Leave a Reply Your email address will not be published. Required fields are marked * Comment

Name *

Email *

Website

POST COMMENT

DOWNLOAD ANDROID APP

RECOMMENDED TUTORIALS

Java Tutorials › Java IO › Java Regular Expressions › Multithreading in Java › Java Logging › Java Annotations › Java XML › Collections in Java › Java Generics › Exception Handling in Java › Java Reflection › Java Design Patterns › JDBC Tutorial

Java EE Tutorials › Servlet JSP Tutorial › Struts2 Tutorial › Spring Tutorial › Hibernate Tutorial › Primefaces Tutorial › Apache Axis 2 › JAX-RS › Memcached Tutorial

Ad

Start your free trial today. Look like an expert right from the start with one of our award-winning designer templates. Squarespace

Visit Site

© 2018 · Privacy Policy · Don't copy, it's Bad Karma · Powered by WordPress

Smile Life

When life gives you a hundred reasons to cry, show life that you have a thousand reasons to smile

Get in touch

© Copyright 2015 - 2024 PDFFOX.COM - All rights reserved.