package com.ming.test import scala.collection.mutable.ArrayBuffer import scala.io.Source import java.awt.image.BufferedImage import javax.imageio.ImageIO import 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好多规则,好晕好绕。。。
时间: 2024-10-17 05:35:50