第58讲:Scala中Abstract Types实战详解

时间:2023-03-08 20:43:03

这一讲我们来学习下抽像类型。让我们看下代码

package scala.learn
import scala.io.BufferedSource
import scala.io.Source

trait Reader{
  type In
  type Contents
  def read(in:In):Contents
}

class FileReader extends Reader{
  type In = String
  type Contents = BufferedSource
  override def read(name:In) = Source.fromFile(name) 
}

object test58{
  def main(args:Array[String]){
    val fileReader = new FileReader
    val content = fileReader.read("E:\\WorkHard\\BIGDATA\\spark\\sparktest\\scala.txt")
    for (line <- content.getLines()){
      println(line)
    }
  }
}

首先,在Reader特质中,定义了抽像类型In和Contents,并不指明具体类型。

在FileReader特质中,继承Reader,并定义具体的抽像类的类型,并重写read函数。

分享下更多的scala资源吧:

百度云盘:http://pan.baidu.com/s/1gd7133t

微云云盘:http://share.weiyun.com/047efd6cc76d6c0cb21605cfaa88c416

360云盘: http://yunpan.cn/cQN9gvcKXe26M (提取码:13cd)

信息来源于 DT大数据梦工厂微信公众账号:DT_Spark

关注微信账号,获取更多关于scala学习内容