• scala泛型


    package com.ming.test
    
    /**
     * scala泛型
     * 类型参数测试
     */
    object TypeParamsTest {
      
      //泛型函数
      def getMiddle[T](a:Array[T])=a(a.length/2)
      
       //类型通配符
      def process1(people:java.util.List[_<:Student])={}
      
      def main(args: Array[String]): Unit = {
        val p=new Pair(42,"String")
        val p2=new Pair[Any,Any](42,"ddd")
        
        val c=new Compare("A","B");
        println(c.smaller)
      }
      
    }
    //定义一个类型参数的类
    class Pair[T,M](var one:T,var two :M)
    
    
    //T必须是Comparable[T]的子类型.
    class Compare[T<:Comparable[T]](val one:T,val two : T){
      def smaller=if(one.compareTo(two)<0) one else two
    }
    
    
    //视图界定
    /**
     * <%关系意味这T可以被隐式转换成Comparable[T],还可以用Ordered特质
     */
    class PairT[T <% Comparable[T]]
    
    class PairTT[T <% Ordered[T]](val one:T,val two:T){
      def smaller=if(one<two) one else two
    }
    
    //上下文界定
    class P[T : Ordering](val one:T,val two:T){
      def smaller(implicit ord: Ordering[T])=
        if(ord.compare(one, two)<0) one else two
    }
    
    //Manifest上下文界定
    class ManfiestTest{
      def makePair[T : Manifest](one:T,two :T){
        val r=new Array[T](2)
        r(0)=one
        r(1)=two
      }
    }
    
    //多重界定,其实就是限定类型范围
    class A[T <:Comparable[T] with Serializable with Cloneable]
    
    class B[T <% Comparable[T] <% String]
    
    class C[T : Ordering : Manifest]
    
    class D[T >: String <:String]
    
    
    abstract class List[+T]{
      def isEmpty :Boolean
      def head :T
      def tail: List[T]
    }
    
    object Empty extends List[Nothing]{
      def isEmpty=true
      def head=throw new UnsupportedOperationException
      def tail=throw new UnsupportedOperationException
    
    }
    
    class Student{}

    scala的泛型比java的要复杂点

  • 相关阅读:
    linux一行执行多条命令 shell
    创建右键nushell打开UTF8(似乎需要win10 1803版本以上,admin的不需要)
    uniapp零碎总结
    nginx https配置问题
    ElasticSearch随记
    ElasticSearch修改index增加字段
    分区表创建和查询
    netfinal
    Mysql 命令操作
    【2022.06.23】python连接数据库
  • 原文地址:https://www.cnblogs.com/huzi007/p/6149994.html
Copyright © 2020-2023  润新知