链接值类调用

时间:2013-12-04 22:37:01

标签: scala value-class

是否可以在没有实际实例化的情况下链接值类?例如:

import scala.swing._

object SwingPlus {
  implicit class RichComponent(val self: Component) extends AnyVal {
    def clientProps: ClientProperties = new ClientProperties(self)
  }

  implicit class ClientProperties(val self: Component) extends AnyVal {
    def += (kv: (String, Any)): Component = {
      self.peer.putClientProperty(kv._1, kv._2)
      self
    }
  }
}

用例:

import SwingPlus._
val b = Button("Foo") { println("bar") }
b.clientProps += "JButton.buttonType" -> "textured"
val f = new Frame { contents = but; pack(); open() }

在调用b.clientProps +=中,ClientProperties是否实例化,或者这些只是纯静态(优化)方法调用?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

看起来就是这样:

val b = Button("Foo") { println("bar") }
b.clientProps += "JButton.buttonType" -> "textured"

拆卸:

   18:  invokevirtual   #33; //Method scala/swing/Button$.apply:(Ljava/lang/String;Lscala/Function0;)Lscala/swing/Button;
   21:  putfield    #10; //Field b:Lscala/swing/Button;
   24:  getstatic   #38; //Field SwingPlus$ClientProperties$.MODULE$:LSwingPlus$ClientProperties$;
   27:  getstatic   #43; //Field SwingPlus$RichComponent$.MODULE$:LSwingPlus$RichComponent$;
   30:  getstatic   #48; //Field SwingPlus$.MODULE$:LSwingPlus$;
   33:  aload_0
   34:  invokevirtual   #50; //Method b:()Lscala/swing/Button;
   37:  invokevirtual   #54; //Method SwingPlus$.RichComponent:(Lscala/swing/Component;)Lscala/swing/Component;
   40:  invokevirtual   #57; //Method SwingPlus$RichComponent$.clientProps$extension:(Lscala/swing/Component;)Lscala/swing/Component;
   43:  getstatic   #62; //Field scala/Predef$ArrowAssoc$.MODULE$:Lscala/Predef$ArrowAssoc$;
   46:  getstatic   #67; //Field scala/Predef$.MODULE$:Lscala/Predef$;
   49:  ldc #69; //String JButton.buttonType
   51:  invokevirtual   #73; //Method scala/Predef$.any2ArrowAssoc:(Ljava/lang/Object;)Ljava/lang/Object;
   54:  ldc #75; //String textured
   56:  invokevirtual   #79; //Method scala/Predef$ArrowAssoc$.$minus$greater$extension:(Ljava/lang/Object;Ljava/lang/Object;)Lscala/Tuple2;
   59:  invokevirtual   #83; //Method SwingPlus$ClientProperties$.$plus$eq$extension:(Lscala/swing/Component;Lscala/Tuple2;)Lscala/swing/Component;