自动装箱拆箱是java中的概念
implicit是scala中的概念
都有变量包装的特性

java的装箱对象

以int与Integer为例对比

  • int变量必须有值,而Integer对象可以为null
  • Integer对象既然是对象,还可以有n种行为(虽然知道,但容易忽略)

Integer本质就是个包装对象, 仅仅这样貌似很普通

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Integer2{
    final int value;
    public Integer2(int value) {
        this.value = value;
    }
    // n个方法意味着还有n种行为
    public void show(){
        System.out.println("值为:" + value);
    }
}

在加上拆装箱时 Integer a = 1; int b = a + 1;
这时候隐含了自动装箱拆箱操作,给人感觉在把对象当成了基本数据类型在用。
不过这种自动化操作仅仅只能在Inter,Long等对象上使用

scala版本的自动装箱拆箱

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.fluffy.test_implicit

object Test2_X_Add_Y {

  class IntBox(init: Int) {
    var money: Int = init

    def add(p1: IntBox): IntBox = {
      money = money + p1.money
      return this
    }

    def -(p1: IntBox): IntBox = {
      money = money - p1.money
      return this
    }
  }

  implicit def autoboxing(x: Int): IntBox = new IntBox(x)

  implicit def unboxing(x: IntBox): Int = x.money

  def main(args: Array[String]): Unit = {
    // 简单示例--创建两个对象
    val p1 = new IntBox(11)
    val p2 = new IntBox(66)
    val p3: Int = p2 - p1 //本来返回了p2对象,却被拆箱了
    println("简单的减法操作", p3)

    // 更多示例--4个
    // x + y 的多种隐式转换
    case1 //  convert(x) + y
    case2 // 隐式转换2: x + convert(y)
    case3 // 隐式转换3: x + convert(y)
    case4 // 隐式转换4:convert(x) + convert(y)

    // 最简化的示例
    implicit def autoboxing2(x: Int) = new {
      def addv2(y: Int): Int = {
        x + y
      }
    }
    val p4 = 11.addv2(22)
    val p5 = 33 addv2 44
    println("装箱拆箱-" + p4, p5)

  }

  def case1 { // 隐式转换1:convert(x) + y
    val x = 10
    val y = new IntBox(20)
    val p1 = x.add(y)
    println("转换" + p1.money)
  }

  def case2 { // 隐式转换2: x + convert(y)
    val x = new IntBox(20)
    val y = 20
    val p1 = x.add(y)
    println("转换" + p1.money)
  }

  def case3 { // 隐式转换3: x + convert(y)
    val x = new IntBox(20)
    val y: IntBox = 20
    val p1 = x.add(y)
    println("转换" + p1.money)
  }

  def case4 { // 隐式转换4:convert(x) + convert(y)
    val p1 = 10.add(20)
    println("转换" + p1.money)
  }

}

思考

过去觉着Integer也是一种int
主要把Integer用在了实体类的属性定义上
自动装箱拆箱这一功能由于在java种的局限性,所以被自动忽略了

scala的隐式转换功能,原义为给对象灵活的添加方法。 刚接触时,总感觉怪怪的。
后来将scala的implicit与Java中的自动装箱拆箱对比思考后,感觉又不一样了。