博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Scala for the Impatients---(10)Traits
阅读量:5313 次
发布时间:2019-06-14

本文共 1387 字,大约阅读时间需要 4 分钟。

Traits as Interfaces

Let’s start with something familiar. A Scala trait can work exactly like a Java interface. For example:

trait Logger {    def log(msg: String) // An abstract method}

A subclass can provide an implementation:

class ConsoleLogger extends Logger { // Use extends, not implements    def log(msg: String) { println(msg) } // No override needed}

If you need more than one trait, add the others using the with keyword: All Java interfaces can be used as Scala traits.

class ConsoleLogger extends Logger with Cloneable with Serializable

Traits with def, val and var

Never use val in a trait for abstract members and use def instead. . 

Traits with Concrete Implementations

In Scala, the methods of a trait need not be abstract.

trait ConsoleLogger {def log(msg: String) { println(msg) }}

Here is an example of using this trait:

class SavingsAccount extends Account with ConsoleLogger {def withdraw(amount: Double) {if (amount > balance) log("Insufficient funds")else balance -= amount}...}

Note the difference between Scala and Java. The SavingsAccount picks up a concrete implementation from the ConsoleLogger trait. This would not be possible with a Java interface.

Objects with Traits

You can add a trait to an individual object when you construct it.

trait Logged {def log(msg: String) { }//do nothing implementation}

 

转载于:https://www.cnblogs.com/chaseblack/p/5879262.html

你可能感兴趣的文章
混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集。...
查看>>
jQuery总结或者锋利的jQuery笔记二
查看>>
微软职位内部推荐-Sr. SE - Office incubation
查看>>
微软职位内部推荐-SOFTWARE ENGINEER II
查看>>
centos系统python2.7更新到3.5
查看>>
【Quartz】常用方法的使用方式(三)
查看>>
MVVM模式下关闭窗口的实现
查看>>
C#区域截图——调用API截图
查看>>
c#与java中byte字节的区别及转换方法
查看>>
A WebBrowser Toy
查看>>
用MyXls生成Excel报表(C#)
查看>>
了解WP的传感器
查看>>
阅读笔记 火球——UML大战需求分析 2
查看>>
acedEvaluateLisp函数的反汇编
查看>>
Linux无线工具详解(Wireless tools for Linux)
查看>>
ACM PKU 2328 http://acm.pku.cn/JudgeOnline/problem?id=2328
查看>>
VB.NET 制作DLL动态库文件
查看>>
RSS阅读器
查看>>
微信电脑版不断崩溃
查看>>
js链式调用
查看>>