scala 主构造器_Scala主构造器深度

本文深入探讨了Scala的主构造器,通过实例介绍了如何使用主构造器,包括无参数、带有参数的构造器以及主构造器中val和var的用法。文章还提到了主构造器的组成部分,如类定义中的参数、类体内的语句和表达式、方法调用以及字段定义。
摘要由CSDN通过智能技术生成

scala 主构造器

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

在这篇文章中,我们将通过实时场景示例深入讨论Scala主构造器。

发表简短目录 (Post Brief TOC)

  • Introduction

    介绍
  • Primary Constructor in Scala

    Scala的主要构造函数
  • Scala val and var in-brief

    Scala Val和var简要介绍
  • Scala Primary Constructor With val and var

    Scala具有val和var的主要构造函数
  • Scala Primary Constructor in-brief

    Scala主要构造函数简述

介绍 (Introduction)

As we know, Constructor is used to create instances of a class. Scala supports constructors in different way than in Java.

众所周知,构造函数用于创建类的实例。 Scala以与Java不同的方式支持构造函数。

In Scala Language, a class can have two types of constructors:

在Scala语言中,一个类可以具有两种类型的构造函数:

  • 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.

Scala类只能包含主构造函数,也可以包含主构造函数和辅助构造函数。 一个Scala类可以包含一个并且只能包含一个Primary构造函数,但是可以包含任意数量的Auxiliary构造函数。 我们将在这篇文章中详细讨论主要构造函数,而在我的后续文章中将讨论辅助构造函数的细节。

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.

类主体用两个大括号“ {}”定义。 第一行是类定义。

Scala的主要构造函数 (Primary Constructor in Scala)

In Scala, a Primary Constructor is a Constructor which starts at Class definition and spans complete Class body.

在Scala中,主要构造函数是一个从Class定义开始并跨越完整Class主体的构造函数。

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.

示例1:-使用默认的Primary Constructor创建一个Person类。

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.

在这里,我们定义了无参数或零参数构造函数,如“ Person()” 。 在Java中也称为“默认构造函数”。

We can create an instance of Person class as shown below:

我们可以创建一个Person类的实例,如下所示:

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

Both are valid in Scala. We can use No-Arguments constructor without parenthesis.

两者均在Scala中有效。 我们可以使用不带括号的No-Arguments构造函数。

Example-2:-
Primary Constructor’s parameters are declared after the class name as shown below:

示例2:-
在类名之后声明主要构造函数的参数,如下所示:

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.

在此,Person类的主要构造函数具有三个参数:firstName,middleName和lastName。

Now, We can create an instance of Person class as shown below:

现在,我们可以创建一个Person类的实例,如下所示:

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).

如果我们观察该示例,则某些人员可能具有中间名,但仍必须提供所有3个参数。 这不是在Scala中处理构造函数的有效方法。 我们可以使用辅助构造函数来解决此问题(请阅读我的下一篇文章)。

Example-3:-
Anything we place within the Class Body other than Method definitions, is a part of the Primary Constructor.

示例3:-
除了方法定义外,我们放在类主体中的所有内容都是主构造函数的一部分。

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:

当在Scala REPL中执行上述程序时,我们将获得以下输出:

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.

如果我们观察到该输出,因为两个println语句都在类主体中定义,则它们将成为主构造函数的一部分。

Example-4:-:-
Any Statements or Loops (like If..else, While,For etc) defined in the Class Body also become part of the Primary Constructor.

示例4:- :-
类主体中定义的任何语句或循环(如If..else,While,For等)也将成为主构造函数的一部分。

class Person(firstName:String, middleName:String, lastName:String){
      
      def fullName() = firstName + middleName + lastName

      if (middleName.trim.length ==0)
          println("Middle Name is empty.")
}

Output:-

输出:-

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.

示例5:- :-
不仅是语句或表达式,在类主体中定义的任何方法调用也将成为主构造函数的一部分。

class Person(firstName:String, middleName:String, lastName:String){
      
      def fullName() = firstName + middleName + lastName

      fullName   // A No-argument Method Call
}

Output:-

输出:-

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

Scala Val和var简要介绍 (Scala val and var in-brief)

Before discussing about Scala Primary Constructor, we need to revisit about Scala Field definitions concept.

在讨论Scala主构造函数之前,我们需要重新了解Scala字段定义概念。

In Scala, “val” and “var” are used to define class fields, constructor parameters, function parameters etc.

在Scala中,“ val”和“ var”用于定义类字段,构造函数参数,函数参数等。

  • “val” means value that is constant. “val” is used to define Immutable Fields or variables or attributes.

    “ val”是指恒定的值。 “ val”用于定义不可变字段或变量或属性。
  • 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.

    “ var”表示不是恒定的变量。 “ var”用于定义可变字段或变量或属性。
  • Mutable fields means once we create, we can modify them.

    可变字段表示创建后就可以对其进行修改。

Scala具有val和var的主要构造函数 (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.

在Scala中,我们可以使用val和var来定义Primary Constructor参数。 我们将通过简单的示例讨论每种情况,并观察一些Scala内部原理。

We have defined three different Scala sources files as shown below:

我们定义了三个不同的Scala源文件,如下所示:

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.

示例1:-
在Scala中,如果我们使用“ var”定义主要构造函数的参数,则Scala编译器将为其生成setter和getter方法。

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:

在“源文件”可用文件夹中打开命令提示符,并编译“ Person1.scala”,如下所示:

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:

此步骤在同一文件夹中创建“ Person1.class”文件。 “ javap”命令是Java类文件反汇编程序。 使用此命令反汇编“ Person1.class”以查看其内容,如下所示:

As per this output, we can say that “var” is used to generate setter and getter for constructor parameters.

根据此输出,我们可以说“ var”用于生成构造函数参数的setter和getter。

As per Scala Notation, setter and getter methods for firstName Parameter:

按照Scala表示法,firstName参数的setter和getter方法:

Getter Method

吸气法

public java.lang.String firstName();

Setter 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.

此“ firstName_ $ eq”方法名称等于“ firstName_ =”。 当我们在标识符定义(类名称,参数名称,方法名称等)中使用“ =”时,它将由Scala编译器自动转换为“ $ eq”标识符。

NOTE:-
Scala does not follow the JavaBeans naming convention for accessor and mutator methods.

注意:-
Scala的访问器和更改器方法不遵循JavaBeans命名约定。

Example-2:-
In Scala, if we use “val” to define Primary Constructor’s parameters, then Scala compiler will generate only getter methods for them.

示例2:-
在Scala中,如果我们使用“ val”来定义主要构造函数的参数,则Scala编译器将仅为其生成getter方法。

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:

打开命令提示符,进行编译并使用“ javap”进行反汇编以查看生成的Java代码,如下所示:

If we observe this output, we can say that “val” is used to generate only getter for constructor parameters.

如果观察到此输出,则可以说“ val”仅用于生成构造函数参数的getter。

As per Scala Notation, getter methods for firstName, middleName and lastName Parameters:

按照Scala表示法,firstName,middleName和lastName参数的getter方法:

Getter Methods

吸气方法

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.

示例3:-
在Scala中,如果我们不使用“ var”和“ val”来定义主要构造函数的参数,则Scala编译器不会为它们生成setter和getter方法。

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:

打开命令提示符,进行编译并使用“ javap”进行反汇编以查看生成的Java代码,如下所示:

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

如果观察到此输出,则可以说没有为firstName,middleName和lastName构造函数参数生成setter和getter方法。

Scala主要构造函数简述 (Scala Primary Constructor in-brief)

The Scala Primary Constructor consist of the following things:

Scala主要构造函数包括以下内容:

  • 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.

用简单的话来说,在类主体中定义的任何方法(方法声明除外)都是Scala主要构造函数的一部分。

That’s it all about Scala Primary Constructor. We will discuss Scala Auxiliary Constructors in-depth in coming posts.

关于Scala主要构造函数的所有内容。 我们将在以后的文章中深入讨论Scala辅助构造函数。

Please drop me a comment if you like my post or have any issues/suggestions.

如果您喜欢我的帖子或有任何问题/建议,请给我评论。

翻译自: https://www.journaldev.com/9810/scala-primary-constructor-indepth

scala 主构造器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值