1

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

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被实例化,或者这些只是纯静态(优化)方法调用?

4

2 回答 2

2

它们是静态调用。这就是价值类所做的:http: //vptheron.github.io/blog/2013/11/02/a-word-of-implicit-conversions-and-value-classes/

于 2013-12-05T00:09:27.323 回答
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;
于 2013-12-05T01:58:34.080 回答