美文网首页
Scala 关键字辨析

Scala 关键字辨析

作者: gs要加油呀 | 来源:发表于2020-01-11 01:03 被阅读0次

由于Chisel基于Scala语言构建,为了更好理解Chisel语言实现中的细节,本文整理了一些有关Scala基本语言特性。

以下关键字若非特别标注,均指代Scala中的

1. Trait

Traits can identifies as “Interfaces that can provide concrete members”.

trait关键字类似于Java中的Interface,不过可以有具体的成员变量

1.1 Traits(Scala) vs Interfaces(Java)

Traits can have abstract members(both fields and methods) as well as concrete members. This is the main difference between Java interfaces and traits.

trait 既可以定义抽象的成员(属性和方法),也可以定义具体的成员。


trait Language {
  // abstract
  var name: String
  
  // concrete
  val maxUsage = 10     
  
  // abstract
  def lang(): Unit         
  
  // concrete 
  def read() = {
    print("Reading")
  }
}

1.2 Traits vs Abstract classes

Traits doesn’t comes with constructor. That is the main difference between traits and abstract classes.

与abstract class相比,trait 没有构造器(constructor)

// this won't compile
trait Language(name: String)

// Use abstract class when needs to have constrctor arguments
abstract class Language(name: String)

1.3 Traits 多继承

trait 支持多继承,当出现类似“菱形继承”的问题时,对于可能冲突的方法或成员,trait的解决方案是继承最右边超类中的方法或成员

If there are multiple implementors of a given member, the implementation in the super type that is furthest to the right (in the list of super types) wins.

trait Language {
  def lang(): Unit
}

trait Functional extends Language {
  override def lang() {
    println("Functional")
  }
}

trait ObjectOriented extends Language {
  override def lang() {
    println("ObjectOriented")
  }
}

class Scala extends Functional with ObjectOriented
new Scala().lang() // output --> ObjectOriented

class Scala extends ObjectOriented with Functional
new Scala().lang() // output --> Functional

1.4 自身类型(self type)引用

特质可以要求混入它的类扩展自另一个类型,但是当使用自身类型(self type)的声明来定义特质时(this: ClassName =>),这样的特质只能被混入给定类型的子类当中。

trait HasBoomAndRocketTiles extends HasTiles
  with CanHavePeripheryPLIC
  with CanHavePeripheryCLINT
  with HasPeripheryDebug
{ this: BaseSubsystem =>
  ...
}

上面这个例子来自rocketchip,HasBoomAndRocketTiles 这个特质只能混入BaseSubsystem的子类中。

2. Abstract class

2.1 Sealed (abstract) classes vs Abstract classes

The difference is that all subclasses of a sealed class (whether it's abstract or not) must be in the same file as the sealed class.

与abstract class 相比,sealed (abstract) class 与其子类必须在同一个文件中。如果子类都明确的情况下,为了防止继承滥用,为抽象类添加sealed

未完待续

参考链接

相关文章

网友评论

      本文标题:Scala 关键字辨析

      本文链接:https://www.haomeiwen.com/subject/jdwmactx.html