首页 > 代码库 > scala一些高级类型

scala一些高级类型

package com.ming.testimport scala.collection.mutable.ArrayBufferimport scala.io.Sourceimport java.awt.image.BufferedImageimport javax.imageio.ImageIOimport java.io.File/** * 高级类型 *///单例类型,链式调用class Document{  def setTitle(title:String)={this}  def setAuthor(author:String)={this}}class Book extends Document{  def addBook(name:String):this.type={this}}//类型投影class NetWork{  class Member(val name:String){    val contacts=new ArrayBuffer[Member]  }  private val members=new ArrayBuffer[Member]  def join(name:String)={    val m=new Member(name)    members+=m    m  }  }//定义Person类,两个泛型参数,分别是S,T,因此//它是可以用中置表达式进行变量定义的case class Person[S,T](val name:S,val age:T)//中置类型-中置类型是代表带有两个参数的类型class ZhongziType{  //下面的代码是一种中置表达方法,相当于  //val p:Person[String,Int]  val p:String Person Int= Person("摇摆少年梦",18)}//抽象类型--类或特质可以定义一个在子类中被具体化的抽象类型trait Reader{  type Contents  def read(fileName : String):Contents}trait Reade1r[T]{   def read(fileName : String):T}//类型Contents是抽象的。具体的子类需要指定这个类型class StringReader extends Reader{  type Contents=String   def read(fileName : String)=Source.fromFile(fileName,"UTF-8").mkString}class ImageReader extends Reader{  type Contents=BufferedImage  def read(fileName :String)=ImageIO.read(new File(fileName))}//object SeniorTypeTest {    def main(args: Array[String]): Unit = {    var d=new Book    var s=d.setAuthor("a").setTitle("hello");    println(s)    var b=new Book    b.addBook("<<helloworld>>").setAuthor("mingge").setTitle("hello")    println(b)  }}

感觉scala好多规则,好晕好绕。。。

scala一些高级类型