隐式类与隐式对象初体验

来源:互联网 发布:baselight调色软件 编辑:程序博客网 时间:2024/05/17 00:17
参考文献
scala 深入浅出实战经典 . 王家林
场景
隐式类与隐式对象语法与简单实用
实验

package com.scode.scala

import java.io.File

import scala.io.Source/** * author: Ivy Peng * function: 隐式类与隐式对象学习 * date:2016/03/28 7.15 * sum: * 1、作用:增强类或对象的功能 * 2、语法:implicit class CLASSNAME | implicit object OBJECTNAME */object Context_Helper2{  implicit class FileEnhancer(file:File)  {    def read2 = Source.fromFile(file.getPath).mkString  }  implicit class Op(x:Int)  {    def myAdd(second:Int)=x+second  }}abstract class Template[T]{  def add(x:T,y:T):T}abstract class SubTemplate[T]{  def unit:T}object Implicit_Object_Class{  def main(args: Array[String]): Unit =  {    /*     * 隐式对象     * 疑问:object 可以 extends 一个类 ? 神奇啊     */    implicit object StringAdd extends SubTemplate[String]    {        def add(x:String,y:String) = x + y        def unit:String = ""    }    implicit object IntAdd extends SubTemplate[Int]    {        def add(x:Int,y:Int)=x+y        def unit:Int = 0    }    // ? 这里  SubTemplate 有 add方法,为什么编译不通过//    def sum[T](xs:List[T])(implicit m:SubTemplate[T]):T=//    {      // value add is not a member of com.scode.scala.SubTemplate[T] //      if(xs.isEmpty) m.unit else m.add(xs.head,sum(xs.tail))//    }        println(StringAdd.add("Hello", "Java"))    println(IntAdd.add(3, 5))         /*     * 隐式类     */    import Context_Helper2._    //powerfull    println(1.myAdd(2))    println(new File("D:\\txt.txt").read2)  }}


0 0