首页 > 技术文章 > Scala学习笔记(五):Trait(特质)

studyLog-share 2015-08-28 17:15 原文

Trait 的一个主要用法,将一个瘦接口变成胖接口

 

trait Philosophical{
    def philosophize(){
        println("here")
    }
}

class Forg extends Philosophical{
    override def toString="green"
}

val forg=new Forg
forg.philosophize

 

typeclass模式

 

trait Tellable[T] {
  def tell(t: T): String
}

case class Color(descript: String)

case class Person(name: String)

object colorTeller extends Tellable[Color] {
    def tell(t: Color): String = "I am color "+t.descript
}

val personTeller = new Tellable[Person] {
    def tell(t: Person): String = "I am "+ t.name
}

def tell[T](t: T)(M: Tellable[T]) = {
    M.tell(t)
}

应用:

tell(Color("RED"))(colorTeller)

tell(Person("John"))(personTeller)

 

应用implicit

 案例一:

object TestTrait {
  
  trait Tellable[T] {
    def tell(t: T): String
  }

  case class Color(descript: String)

  implicit object colorTeller extends Tellable[Color] {
    def tell(t: Color): String = "I am color "+t.descript

  }

  def main(args: Array[String]): Unit = {
    
    import colorTeller._

    println(tell(Color("RED")))
  }
}

 

案例二:

  trait Monoid[A] {
    def mappend(a1: A, a2: A): A

    def mzero: A
  }

  implicit object intMonoid extends Monoid[Int] {
    def mappend(i1: Int, i2: Int): Int = i1 + i2

    def mzero = 0
  }

  implicit object stringMonoid extends Monoid[String] {
    def mappend(s1: String, s2: String): String = s1 + s2

    def mzero = ""
  }

  def sum[A](xs: List[A])(implicit m: Monoid[A]): A = xs.foldLeft(m.mzero)(m.mappend)

  //> sum: [A](xs: List[A])(implicit m: scalaz.learn.ex2.Monoid[A])A
  sum(List(1, 2, 3)) //> res0: Int = 6
  sum(List("Hello,", " how are you")) //> res1: String = Hello, how are you

 

Application Trait

Scala提供了特质scala.Application,在单例对象名后面写上“extends Application”,把想要执行的代码直接放在单例对象的花括号之间

import ChecksumAccumulator.calculate

object FallWinterSpringSummer extends Application {

for (season <- List("fall", "winter", "spring"))
  println(season +": "+ calculate(season))
}

能这么做,是因为特质Application声明了带有合适签名的main方法,并被你写的单例对象继承

花括号之间的代码被收集进了单例对象的主构造器,并在类初始化时执行

 

优点:

1.可以减少一些输入工作

 

缺点:

1.不能访问命令行参数

 

Ordered Trait

 

 

推荐阅读