scala 类的多态

The methods in scala can be parametrized with both value and types. Value parameters are enclosed within a pair of parenthesis whereas type parameters within a pair of brackets. For example;

scala中的方法可以使用值和类型进行参数化。 值参数括在一对括号内,而类型参数括在一对括号内。 例如;

polymorphic.scala

polymorphic.scala

object polymorphic {def main(args: Array[String]) {def add(a: Int, b: Int) {val c = a + b;println(c)}def addStrings(a: String, b: String) {val s = a + bprintln(s)}add(72, 67);addStrings("Hello", "World");}
}

In this example the + plus operator is used for adding numbers as well as concatenating the strings. The add method performs the addition of two numbers and returns the result. The addString method use the same + operator and concatenates the two strings specified by the user. This is default operator polymorphism provided by Scala. Below image shows the output produced by the above program.

在此示例中,+加号运算符用于添加数字以及连接字符串。 加法执行两个数字的加法并返回结果。 addString方法使用相同的+运算符,并连接用户指定的两个字符串。 这是Scala提供的默认运算符多态性。 下图显示了以上程序产生的输出。

Scala方法多态 (Scala Method Polymorphism)

Now let’s see an example of polymorphism in method. We will write a generic method to get the list where we will pass the type, default values and number of items in the list.

现在让我们看一个方法中多态的例子。 我们将编写一个通用方法来获取列表,并在其中传递列表中的类型,默认值和项目数。

PolymorphicMethod.scala

PolymorphicMethod.scala

object PolymorphicMethod {def getList[T](x:T, y:Int): List[T] = {if (y == 0)Nilelsex :: getList(x, y - 1)}def main(args: Array[String]) {println(getList[Int](3,2))println(getList[String]("Hi", 3))}
}

Below image shows the output produced when above program is executed in the Scala IDE.

下图显示了在Scala IDE中执行上述程序时产生的输出。

Scala明确键入引用 (Scala Explicitly typed References)

Sometimes we need to explicitly specify the type of value “this” in a program. Let’s see an example for this scenario.

有时我们需要在程序中显式指定值“ this”的类型。 让我们看一下这种情况的例子。

We have a Train abstract class as below.

我们有一个Train抽象类,如下所示。

Train.scala

Train.scala

abstract class Train {type Link;type Compartment <: CompartmentIntfabstract class CompartmentIntf {def join(compartment: Compartment): Link}def compartments: List[Compartment]def links: List[Link]def addCompartment: Compartment
}

The abstract class Train consists of List of links and compartments. The abstract class CompartmentIntf is defined and contains join method which takes Compartment as parameter. The methods compartments, links and addCompartment are declared but the implementation will be defined in concrete classes.

抽象类Train由链节和车厢列表组成。 定义了抽象类CompartmentIntf ,并包含将Compartment作为参数的join方法。 方法隔离区,链接和addCompartment被声明,但是实现将在具体类中定义。

Now we will define the abstract class MetroTrain that extends train class as;

现在,我们将定义抽象类MetroTrain,将火车类扩展为;

MetroTrain.scala

MetroTrain.scala

abstract class MetroTrain extends Train {type Link <: LinkImplclass LinkImpl(comptA: Compartment, comptB: Compartment) {def c1 = comptAdef c2 = comptB}class CompartmentImpl extends CompartmentIntf {def join(compartment: Compartment): Link = {val link = newLink(this, compartment)links = link :: linkslink}}protected def newCompartment: Compartmentprotected def newLink(c1: Compartment, c2: Compartment): Linkvar compartments: List[Compartment] = Nilvar links: List[Link] = Nildef addCompartment: Compartment = {val compartment = newCompartmentcompartments = compartment :: compartmentscompartment}
}

This class provides a partial implementation extending Train class. The implementation details are open and thus link and compartment are left abstract. We add factory methods newLink and newCompartment since it is required to create new compartment and link objects. The methods addCompartment and join are defined using factory methods.

此类提供了扩展Train类的部分实现。 实现细节是开放的,因此链接和隔离专区被抽象化了。 由于创建新的隔离专区和链接对象是必需的,因此我们添加了工厂方法newLink和newCompartment。 方法addCompartment和join是使用工厂方法定义的。

However above class will throw compilation error in line no 11 as “type mismatch; found : CompartmentImpl.this.type (with underlying type MetroTrain1.this.CompartmentImpl) required: MetroTrain1.this.Compartment” because “this” is assigned the type CompartmentImpl, so it’s not compatible with type Compartment required by the corresponding factory method.

但是,上述类将在第11行中将编译错误抛出为“ 类型不匹配; 找到:CompartmentImpl.this.type(具有基本类型MetroTrain1.this.CompartmentImpl):MetroTrain1.this.Compartment,因为“ this”被分配了CompartmentImpl类型,因此它与相应工厂方法所需的Compartment类型不兼容。

Let us solve this type mismatch by using explicitly typed self reference for CompartmentImpl as below.

让我们通过如下使用CompartmentImpl显式类型自引用来解决此类型不匹配的问题。

class CompartmentImpl extends CompartmentIntf {self: Compartment =>def join(compartment: Compartment): Link = {val link = newLink(this, compartment)links = link :: linkslink}
}

According to the new definition of CompartmentImpl, this has type Compartment. We specify the explicit typed reference so that CompartmentImpl denotes sub type of Compartment to be instantiate.

根据CompartmentImpl的新定义,此类型为Compartment。 我们指定显式类型的引用,以便CompartmentImpl表示要实例化的Compartment的子类型。

We will now define a concrete class ConcreteMetroTrain as;

现在,我们将一个具体的类ConcreteMetroTrain定义为;

ConcreteMetroTrain.scala

ConcreteMetroTrain.scala

class ConcreteMetroTrain extends MetroTrain {type Link = LinkImpltype Compartment = CompartmentImplprotected def newCompartment: Compartment = new CompartmentImplprotected def newLink(c1: Compartment, c2: Compartment): Link =new LinkImpl(c1, c2)
}

We can now instantiate CompartmentImpl because now we know that CompartmentImpl denotes a subtype of type Compartment. Now create a Scala object TestTrain as;

现在我们可以实例化CompartmentImpl,因为现在我们知道CompartmentImpl表示Compartment类型的子类型。 现在创建一个Scala对象TestTrain作为;

TestTrain.scala

TestTrain.scala

object TestTrain {def main(args: Array[String]) {println("Linking Compartments.....")val t: Train = new ConcreteMetroTrainval c1 = t.addCompartmentval c2 = t.addCompartmentval c3 = t.addCompartmentc1.join(c2)c2.join(c3)}
}

That’s all for polymorphic methods and explicitly typed references in scala programming, we will look into more scala features in coming posts.

这一切都用于scala编程中的多态方法和显式键入的引用,我们将在以后的文章中研究更多的scala功能。

翻译自: https://www.journaldev.com/8495/scala-polymorphic-methods-and-explicitly-typed-references

scala 类的多态

scala 类的多态_Scala多态方法和显式引用相关推荐

  1. scala类的序列化_Scala序列理解,通用类和内部类示例

    scala类的序列化 A sequence comprehension statement consists of a generator part which generates a list of ...

  2. 基类显式继承接口,类继承基类时又继承同一接口,引发接口方法混乱(显式继承接口的弊端)...

    基类BaseOutput显式继承了一个接口IOutput,之后类TrackOutput继承BaseOutput,同时又继承了IOutput接口,假定IOutput有方法Output,这样在TrackO ...

  3. Python类与对象最全总结大全(类、实例、属性方法、继承、派生、多态、内建函数)

    目录 面向对象编程 常用术语/名词解释 抽象/实现 封装/接口 合成 派生/继承/继承结构 泛化/特化 多态 自省/反射 访问限制 私有属性和公有属性 私有方法的设置 类 创建类 声明与定义 类属性 ...

  4. 类的继承与多态知识点总结

    一.类的访问权限 class A {private:int x; public:int z; public:void test() {x = 1;//okz = 1;//okA a;a.x = 1;/ ...

  5. python定义方法self会被当作变量_为什么Python必须在方法定义和调用中显式使用“self”?...

    为什么Python必须在方法定义和调用中显示使用"self"? 这个想法借鉴了 Modula-3 语言.出于多种原因它被证明是非常有用的. 首先,更明显的显示出,使用的是方法或实例 ...

  6. C++ day22 继承(二)基类指针数组通过虚方法实现智能的多态

    继承一共有三种: 公有继承 私有继承 保护继承 文章目录 公有继承 基类和派生类的关系 is-a(用公有继承表示"是一种"的关系) has-a uses-a is-like-a i ...

  7. Cola公司的雇员分为以下若干类:(知识点:多态) 4.1 ColaEmployee :这是所有员工总的父类,属性:员工的姓名,员工 的生日月份。方法:getSalary(int month) 根据

    Cola公司的雇员分为以下若干类:(知识点:多态) 4.1 ColaEmployee :这是所有员工总的父类,属性:员工的姓名,员工 的生日月份.方法:getSalary(int month) 根据参 ...

  8. Java SE_封装、继承、object类、super-this关键字、方法重写、多态、instanceof、类型转换

    封装 该露的露,该藏的藏 我们程序设计要追求"高内聚,低耦合".高内聚:类的内部数据操作细节自己完成,不允许外部干涉:低耦合:仅暴露少量的方法给外部使用. 封装(数据的隐藏) 通常 ...

  9. 【C++ 语言】面向对象 ( 继承 | 重写 | 子类调用父类方法 | 静态多态 | 动态多态 | 虚函数 | 纯虚函数 )

    文章目录 类的继承 方法的重写 子类中调用父类方法 多态 虚函数 虚函数示例 纯虚函数 相关代码 类的继承 1. 继承表示 : C++ 中继承可以使用 ":" 符号 , 格式为 & ...

最新文章

  1. 业务系统性能优化——缓存
  2. matlab仿真谱间干扰,内外分解和谱分解问题解析计算及其MATLAB仿真.pdf
  3. 为 Jupyter Notebook指定虚拟环境的 Python 解释器
  4. php如何隐藏入口文件,PHP怎样隐藏入口文件
  5. python变量类型-Python变量类型
  6. 语音特征提取: MFCC的理解
  7. 试图登录,但是网络登陆服务没有启动成功
  8. 使用CSVDE批量创建和修改域用户
  9. 识别PDF文字,教你两招
  10. java 纯真地址库_JAVA解析纯真IP地址库
  11. 文件查找,打包压缩,解压相关分享
  12. 使用 github copilot 踩坑记录:failed to initiate the github login process please try again
  13. C语言简单进制转换器
  14. 设计模式学习之工厂模式(附demo)
  15. proteus仿真数码管
  16. 中国首届敏捷大会纪行
  17. 读论文:LADN: Local Adversarial Disentangling Network for Facial Makeup and De-Makeup
  18. 硬件知识收集总结---20210811
  19. FlowFusion: 基于光流法的动态稠密RGB-D SLAM
  20. apache FtpService 报错421

热门文章

  1. [转载] numpy.arctan, math.atan, math.atan2的区别
  2. [转载] numpy总结
  3. java多线程学习-java.util.concurrent详解(五) ScheduledThreadPoolExecutor
  4. Java设计模式学习记录-解释器模式
  5. Git 笔记——如何处理分支合并冲突
  6. PHP 实例 AJAX 与 MySQL
  7. centos上自动执行脚本执行php文件
  8. 四元数运动学笔记(1)旋转的表示
  9. 变量申明的提升,闭包,作用域,this,运算符优先级详细举例及讲解
  10. 机电传动控制 第一周作业