scala 知识总结 apply与unapply

package org.spafka.apply

class Foo( val foo: String){
  override def toString: String = foo
}

object Foo{
  def apply(foo : String): Foo = {new Foo(foo)}
}

/**
 * @author spafka
 * @modifyer spafka
 * @desc:  查看源码 apply差不多是构造方法的作用
 * @create 2017/9/30 21:34
 **/
object Main extends App{
  println(Foo("foo"))
}

//package org.spafka;

//public final class Foo$
//{
//  public static final  MODULE$;
//
//  static
//  {
//    new ();
//  }
//
//  public Foo apply(String foo)
//  {
//    return new Foo(foo);
//  }
//
//  private Foo$()
//{
//  MODULE$ = this;
//}
//}


package org.spafka.apply

import scala.reflect.ClassTag

object ArrayApply {
  def main(args: Array[String]): Unit = {
    val arr = new Array[Int](3)
    arr(0) = 0
    arr(1) = 1
    arr(2) = 2
    arr.foreach(x => print(x + " "))
    println()

    val array = Array(1,2,3)
    array.foreach(x => print(x + " "))
  }


  /**
   * @author spafka
   * @modifyer spafka
   * @desc:  数组是泛型擦除的,引入Classtag ,隐式引入数组的类型
   * @create 2017/9/30 22:16 
   **/
  def apply[T: ClassTag](xs: T*): Array[T] = {
    val array = new Array[T](xs.length)
    var i = 0
    for (x <- xs.iterator) { array(i) = x; i += 1 }
    array
  }
}

object Main2{
  def main(args: Array[String]): Unit = {
    ArrayApply(1,2,3,4).foreach(println)
  }
}
此处看了下spark源码Rdd都是[T:ClassTag],RDD本质上就是数组,可能理解有误,不吝赐教。
package org.spafka.apply

class Money(val value: Double, val country: String) {}

object Money {
  def apply(value: Double, country: String) : Money = new Money(value, country)

  def unapply(money: Money): Option[(Double, String)] = {
    if(money == null) {
      None
    } else {
      Some(money.value, money.country)
    }
  }

  def main(args: Array[String]): Unit = {
    val money = Money(10.1, "RMB")
    money match {
      case Money(num, "RMB") =>  println("RMB: " + num)
      case _ => println("Not RMB!")
    }
  }
}

/**
 * @author spafka
 * @modifyer spafka
 * @desc: 总的来说apply类似于构造器,
  *       unapply为抽取器,常用于模式匹配的抽取
 * @create 2017/9/30 21:54
 **/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值