当前位置:网站首页>Scala main constructor_ Scala main constructor depth
Scala main constructor_ Scala main constructor depth
2022-07-23 07:50:00 【Wu Nian】
scala primary constructor
In this post, we are going to discuss about Scala Primary Constructor in depth with real-time scenario examples.
In this article , We will discuss in depth through real-time scenario examples Scala primary constructor .
Publish a short catalogue (Post Brief TOC)
- Introduction Introduce
- Primary Constructor in Scala Scala The main constructor of
- Scala val and var in-brief Scala Val and var Brief introduction
- Scala Primary Constructor With val and var Scala have val and var The main constructor of
- Scala Primary Constructor in-brief Scala Brief description of main constructors
Introduce (Introduction)
As we know, Constructor is used to create instances of a class. Scala supports constructors in different way than in Java.
as everyone knows , Constructors are used to create instances of classes . Scala In order to Java Constructors are supported in different ways .
In Scala Language, a class can have two types of constructors:
stay Scala In language , A class can have two types of constructors :
- Primary Constructor Main builders
- Auxiliary 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.
Scala Classes can only contain primary constructors , It can also contain primary constructors and auxiliary constructors . One Scala A class can contain one and only one Primary Constructors , But it can contain any number of Auxiliary Constructors . We will discuss the main constructors in detail in this article , In my subsequent articles, I will discuss the details of auxiliary constructors .
Before going to next sections, we need to understand Class Definition and Class Body as shown in the diagram below:
Before moving on to the next section , We need to understand class definitions and class bodies , As shown in the figure below :
Class Body is defined with two curly braces “{ }”. First line is Class Definition.
The class body uses two braces “ {}” Definition . The first line is the class definition .
Scala The main constructor of (Primary Constructor in Scala)
In Scala, a Primary Constructor is a Constructor which starts at Class definition and spans complete Class body.
stay Scala in , The main constructor is a from Class Define the beginning and span the whole Class The constructor of the 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.
We can define the main constructor with zero or one or more parameters . Now? , We will discuss them one by one through some simple examples .
Example-1:-Create a Person class with default Primary Constructor.
Example 1:- Use default Primary Constructor Create a Person class .
-
class
Person{
-
// Class body goes here
-
}
Here we have defined No-Argument or Zero-Arguments constructor like “Person()”. It is also known as “Default Constructor” in Java.
ad locum , We define parameterless or zero parameter constructors , Such as “ Person()” . stay Java Also known as “ Default constructor ”.
We can create an instance of Person class as shown below:
We can create one Person Class , As shown below :
-
val p1 =
new
Person()
-
-
var p2 =
new
Person
Both are valid in Scala. We can use No-Arguments constructor without parenthesis.
Both are in Scala Effective in . We can use the one without brackets No-Arguments Constructors .
Example-2:-
Primary Constructor’s parameters are declared after the class name as shown below:
Example 2:-
Declare the parameters of the main constructor after the class name , As shown below :
-
class
Person(
firstName:
String,
middleName:
String,
lastName:
String){
-
// Class body goes here
-
}
Here Person class’s Primary Constructor has three parameters: firstName, middleName and lastName.
Here it is ,Person The main constructor of a class has three parameters :firstName,middleName and lastName.
Now, We can create an instance of Person class as shown below:
Now? , We can create one Person Class , As shown below :
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).
If we look at this example , Then some people may have middle names , But you still have to provide all 3 Parameters . This is not Scala An effective way to handle constructors in . We can use auxiliary constructors to solve this problem ( Please read my next article ).
Example-3:-
Anything we place within the Class Body other than Method definitions, is a part of the Primary Constructor.
Example 3:-
In addition to method definitions , Everything we put in the body of the class is part of the main constructor .
-
class
Person(
firstName:
String,
middleName:
String,
lastName:
String){
-
println(
"Statement 1")
-
-
def
fullName() = firstName + middleName + lastName
-
-
println(
"Statement 2")
-
}
When we execute above program in Scala REPL, we can get the following output:
When in Scala REPL When performing the above procedure in , We will get the following output :
-
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.
If we observe this output , Because the two one. println Statements are defined in the class body , Then they will become part of the main 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.
Example 4:- :-
Any statement or loop defined in the class body ( Such as If..else,While,For etc. ) Will also become part of the main constructor .
-
class
Person(
firstName:
String,
middleName:
String,
lastName:
String){
-
-
def
fullName() = firstName + middleName + lastName
-
-
if (middleName.
trim.
length ==
0)
-
println(
"Middle Name is empty.")
-
}
Output:-
Output :-
-
scala>
var p1 =
new Person(
"Ram",
"",
"Posa")
-
Middle Name
is empty.
-
p1: Person = [email protected]
64a40280
Example-5:-:-
Not only Statements or Expressions, any method calls defined in the Class Body also become part of the Primary Constructor.
Example 5:- :-
Not just statements or expressions , Any method call defined in the body of the class will also become part of the main constructor .
-
class Person(firstName:String, middleName:String, lastName:String){
-
-
def fullName() = firstName + middleName + lastName
-
-
fullName // A No-argument Method Call
-
}
Output:-
Output :-
-
scala>
var p1 =
new
Person(
"Ram",
"-",
"Posa")
-
Ram-
Posa
-
p1:
Person =
Person@64a40280
Scala Val and var Brief introduction (Scala val and var in-brief)
Before discussing about Scala Primary Constructor, we need to revisit about Scala Field definitions concept.
In the discussion Scala Before the main constructor , We need to re understand Scala Field definition concept .
In Scala, “val” and “var” are used to define class fields, constructor parameters, function parameters etc.
stay Scala in ,“ val” and “ var” Used to define class fields , constructors parameters , Function parameters, etc .
- “val” means value that is constant. “val” is used to define Immutable Fields or variables or attributes. “ val” Is a constant value . “ val” Used to define immutable fields or variables or attributes .
- Immutable fields means once we create we cannot modify them. Immutable fields indicate that once created , It cannot be modified .
- “var” means variable that is NOT constant. “var” is used to define Mutable Fields or variables or attributes. “ var” Indicates a variable that is not constant . “ var” Used to define variable fields or variables or attributes .
- Mutable fields means once we create, we can modify them. The variable field indicates that it can be modified after creation .
Scala have val and var The main constructor of (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.
stay Scala in , We can use val and var To define Primary Constructor Parameters . We will discuss each case with simple examples , And observe some Scala internals .
We have defined three different Scala sources files as shown below:
We define three different Scala Source file , 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.
Example 1:-
stay Scala in , If we use “ var” Define the parameters of the main constructor , be Scala The compiler will generate setter and getter Method .
Person1.scala
Person1.scala
-
class
Person1(
var
firstName:
String,
-
var
middleName:
String,
-
var
lastName:
String)
Open command prompt at Source Files available folder and compile “Person1.scala” as shown below:
stay “ Source file ” Open the command prompt in the 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:
This step creates... In the same folder “ Person1.class” file . “ javap” The order is Java Class file disassembler . Use this command to disassemble “ Person1.class” To see its contents , As shown below :
As per this output, we can say that “var” is used to generate setter and getter for constructor parameters.
According to this output , We can say “ var” Used to generate constructor parameters setter and getter.
As per Scala Notation, setter and getter methods for firstName Parameter:
according to Scala notation ,firstName Parametric setter and getter Method :
Getter Method
Gettering
public java.lang.String firstName();
Setter Method
Setup method
public void firstName_$eq(java.lang.String);
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.
this “ firstName_ $ eq” Method name equals “ firstName_ =”. When we define the identifier ( Class name , Parameter name , Method name, etc ) Use in “ =” when , It will be Scala The compiler automatically converts to “ $ eq” identifier .
NOTE:-
Scala does not follow the JavaBeans naming convention for accessor and mutator methods.
Be careful :-
Scala Accessor and changer methods of do not follow JavaBeans Naming conventions .
Example-2:-
In Scala, if we use “val” to define Primary Constructor’s parameters, then Scala compiler will generate only getter methods for them.
Example 2:-
stay Scala in , If we use “ val” To define the parameters of the main constructor , be Scala The compiler will only generate getter Method .
Person2.scala
Person2.scala
-
class Person1(val firstName:String,
-
val
middleName:
String,
-
val
lastName:
String)
Open command prompt, compile and use “javap” to disassemble to see the generated Java Code as shown below:
Open Command Prompt , Compile and use “ javap” 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.
If you observe this output , Then we can say “ val” Only used to generate constructor parameters getter.
As per Scala Notation, getter methods for firstName, middleName and lastName Parameters:
according to Scala notation ,firstName,middleName and lastName Parametric getter Method :
Getter Methods
Inspiratory method
-
public java.lang.
String firstName();
-
public java.lang.
String middleName();
-
public java.lang.
String lastName();
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.
Example 3:-
stay Scala in , If we don't use “ var” and “ val” To define the parameters of the main constructor , be Scala The compiler will not generate setter and getter Method .
Person3.scala
Person3.scala
-
class Person1(firstName:String,
-
middleName:
String,
-
lastName:
String)
Open command prompt, compile and use “javap” to disassemble to see the generated Java Code as shown below:
Open Command Prompt , Compile and use “ javap” 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.
If you observe this output , It can be said that there is no for firstName,middleName and lastName Constructor parameter generation setter and getter Method .
Scala Brief description of main constructors (Scala Primary Constructor in-brief)
The Scala Primary Constructor consist of the following things:
Scala The main constructors include the following :
- The constructor parameters declare at Class Definition Constructor parameters are declared in the class definition
- All Statements and Expressions which are executed in the Class Body All statements and expressions executed in the class body
- Methods which are called in the Class Body Methods called in the class body
- Fields which are called in the Class Body Fields called in the body of the class
In Simple words, anything defined within the Class Body other than Method Declarations is a part of the Scala Primary Constructor.
In simple words , Any method defined in the class body ( Except for method declarations ) All are Scala Part of the main constructor .
That’s it all about Scala Primary Constructor. We will discuss Scala Auxiliary Constructors in-depth in coming posts.
About Scala All the contents of the main constructor . We will discuss in depth in future articles Scala Auxiliary constructors .
Please drop me a comment if you like my post or have any issues/suggestions.
If you like my post or have any questions / Suggest , Please give me a comment .
Translated from : https://www.journaldev.com/9810/scala-primary-constructor-indepth
scala primary constructor
边栏推荐
- 局域网SDN硬核技术内幕 20 亢龙有悔——规格与限制(上)
- 2022年暑假ACM热身练习4(总结)
- 程序员最想干的三件事 |漫画
- remove函数的实现
- How to use the order flow analysis tool (Part 2)
- 船舶测试/ IMO A.799 (19)船用结构材料不燃性试验
- Wechat hotel reservation applet graduation project (5) assignment
- 6-14漏洞利用-rpcbind漏洞利用
- LAN SDN technology hard core insider 8 from layer 2 switching to layer 3 routing
- 直播实录 | 37 手游如何用 StarRocks 实现用户画像分析
猜你喜欢
![[ssm] unified result encapsulation](/img/ff/9528a062d464acee52047598af40c3.png)
[ssm] unified result encapsulation

正版Adobe软件来了!Adobe全球唯一正版全家桶订阅只需0元/年

6-13漏洞利用-smtp暴力破解

【09】程序装载:“640K内存”真的不够用么?
![[untitled] share an API Gateway project developed based on ABP vNext](/img/94/bfa4fa36e4974830e6afac118a593e.png)
[untitled] share an API Gateway project developed based on ABP vNext

I use the factory mode in jd.com and explain the factory mode clearly

Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)

Classes et objets (1)

Wechat campus second-hand book trading applet graduation design finished product (5) assignment

93. (leaflet chapter) leaflet situation plotting - modification of attack direction
随机推荐
关于Redis,是先更新数据库,还是先更新缓存?
Wechat campus second-hand book trading applet graduation design finished product (7) Interim inspection report
如何配置CANoe Network-based access模式的以太网网络拓扑
Wechat hotel reservation applet graduation project (6) opening defense ppt
局域网SDN硬核技术内幕 17 从一到百
驱动页面性能优化的3个有效策略
局域网SDN技术硬核内幕 4 从计算虚拟化到网络虚拟化
文件上传,服务器文件名中文乱码文件上传,服务器文件名中文乱码
Understand the domestic open source Magnolia license series agreement in simple terms
局域网SDN技术硬核内幕 6 分布式任意播网关
亚马逊旗下Zoox通过安全测试 并在加州申请试驾
1.11 ArrayList&学生管理系统
局域网SDN硬核技术内幕 20 亢龙有悔——规格与限制(上)
Redis三种集群方案
Inside the hard core of LAN SDN technology - evpn implementation of 16 three from thing to person user roaming in the park
一文深入浅出理解国产开源木兰许可系列协议
我是如何在一周内拿到4份offer的?
FastAPI学习(二)——FastAPI+Jinjia2模板渲染网页(跳转返回渲染页面)
flink批量读取es
Redis——JedisConnectionException Could not get a resource from the pool