0

例如,假设我们有:

object Types {
   type ObjectMap = collection.Map[String, Any]
}

class X {
  def toObjectMap(x:Any): ObjectMap = x.asInstanceOf[Types.ObjectMap] 
}

与以下相比,这是否有任何额外的运行时惩罚:

class X {
  def toObjectMap(x:Any): collection.Map[String, Any]= x.asInstanceOf[collection.Map[String, Any]] 
}
4

2 回答 2

4

我不希望它,但你知道它就像,真的很容易尝试。

scala> :javap -prv X

  public scala.collection.Map<java.lang.String, java.lang.Object> toObjectMap(java.lang.Object);
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=2
         0: aload_1       
         1: checkcast     #9                  // class scala/collection/Map
         4: areturn       
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       5     0  this   L$line9/$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$X;
               0       5     1     x   Ljava/lang/Object;
      LineNumberTable:
        line 53: 0
    Signature: #75                          // (Ljava/lang/Object;)Lscala/collection/Map<Ljava/lang/String;Ljava/lang/Object;>;

  public scala.collection.Map<java.lang.String, java.lang.Object> toObjectMap2(java.lang.Object);
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=2, args_size=2
         0: aload_1       
         1: checkcast     #9                  // class scala/collection/Map
         4: areturn       
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0       5     0  this   L$line9/$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$X;
               0       5     1     x   Ljava/lang/Object;
      LineNumberTable:
        line 54: 0
    Signature: #75                          // (Ljava/lang/Object;)Lscala/collection/Map<Ljava/lang/String;Ljava/lang/Object;>;
于 2013-10-24T00:38:46.853 回答
0

类型别名只是简写。编译器扩展别名,从那时起,就像您自己写出类型一样精确地进行。(正如 Som 的回答所示,至少对于您的特定示例而言。)

于 2013-10-24T01:22:50.870 回答