隐式、泛型

隐式(implicit)
1、隐式参数

     把参数列表标记为 implicit,表示该参数是隐式参数。一个方法只会有一个隐式参数列表,置于方法的最后一个参数列表。如果方法有多个隐式参数,只需一个implicit 修饰即可。

object ImplicitTest {

  implicit val message = "good"
  implicit val age = 100

  /**
   * 如果方法有多个隐式参数,只需一个implicit 修饰即可
   *
   * @param content
   * @param age
   */
  def say(implicit content: String, age: Int): Unit = {
    println(content + "  " + age)
  }

  def main(args: Array[String]): Unit = {
    // 这里调用方法say没有传参,但由于这里定义了了隐式参数 content
    // 且类型也为String,解释器就会找到已经定义好的隐式参数msg
    say
  }
}

2、泛型

package com.smile.tiny

import com.smile.tiny.clothesEnum.clothesEnum

object clothesEnum extends Enumeration {
  type clothesEnum = Value
  val 上衣, 内衣, 裤子, 袜子 = Value
}

abstract class Message[T](s: T) {
  def get: T = s
}

class StrMessage[String](msg: String) extends Message(msg)

class IntMessage[Int](msg: Int) extends Message(msg)

class Clothes[A, B, C](val clothesType: A, var color: B, var siz: C)

object TemplateTest {

  def getData[T](l: List[T]) = {
    l(l.length / 2)
  }

  def main(args: Array[String]): Unit = {
    val msg = new StrMessage[String]("hai")
    val value = new IntMessage[Int](100)
    println(msg.get + " " + value.get)

    val cl = new Clothes[clothesEnum, String, String](clothesEnum.上衣, "红色", "32L")
    println(cl.siz)

    val list = List(1, 2, 3, 4, 5, 6)
    println(getData(list))
  }
}

 

posted on 2023-04-02 13:06  溪水静幽  阅读(6)  评论(0)    收藏  举报