美文网首页
值类型与通用特质

值类型与通用特质

作者: high_m | 来源:发表于2017-11-10 20:53 被阅读0次

    值类型与通用特质是scala特性中一个特别知识点,需要工作使用中慢慢体会

    通用特质

    A universal trait is a trait that extends Any, only has def s as members, and does no initialization.
    

    继承自Any的trait,内部成员只有def定义的方法,且没有初始化语句。

    值类型

    首先看一个最简值类型(官网)

    class Wrapper(val underlying: Int) extends AnyVal {
      def foo: Wrapper = new Wrapper(underlying * 19)
    }
    

    值类型都是要继承AnyVal的,更多的情况下,值类型还会继承通用特质,如下:

    trait Printable extends Any {
      def print(): Unit = println(this)
    }
    //Wrapper是一个值类型,继承了Printable通用特质
    class Wrapper(val underlying: Int) extends AnyVal with Printable
    
    val w = new Wrapper(3)
    //因为继承了普通特质的print方法,招致此处需要实例化Wrapper
    w.print() // actually requires instantiating a Wrapper instance
    

    总结

    • Value类虽然没有显示的用final修饰,但是依然可以认为是final类。

    参考

    1 官方文档
    2 Scala 的Value Class 和 Universal Traits
    3 通用特质(universal traits)

    相关文章

      网友评论

          本文标题:值类型与通用特质

          本文链接:https://www.haomeiwen.com/subject/npfkmxtx.html