zoukankan      html  css  js  c++  java
  • 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的要复杂点

  • 相关阅读:
    docker 001 简介
    Golang 学习笔记 003 标识符、变量和常量
    Golang 学习笔记 002 第一个 go 程序
    Golang 学习笔记 001 环境部署
    nginx配置url中带问号的rewrite跳转
    北京市图书馆免费入口
    编译安装Python3
    Python—进程、线程、协程
    Python—I/O多路复用
    Python—Socket
  • 原文地址:https://www.cnblogs.com/huzi007/p/6149994.html
Copyright © 2011-2022 走看看