简体   繁体   English

如何在Scala中实现`type`关键字

[英]How is the `type` keyword implemented in Scala

Is type in scala just a syntactic sugar that acts like a macro during compile time, or is there some other magic involved? scala中的type仅仅是在编译时充当宏的语法糖,还是涉及其他魔术? In a situation like this: 在这种情况下:

type Bar1 = Foo
type Bar2 = Foo
val bar1 = injector.getInstance(classOf[Bar1])
val bar2 = injector.getInstance(classOf[Bar2])

Would the DI container be able to distinguish between the two 'type aliases' ? DI容器能够区分两个“类型别名”吗?

It's just syntactic sugar that assigns a different name to the same type. 只是语法糖为同一类型分配了不同的名称。 The compiler does not generate a new type so is not able to distinguish type aliases of the same type from each other, or from the original type. 编译器不会生成新类型,因此无法区分相同类型的别名或原始类型的别名。 So for example: 因此,例如:

type Foo = String
def foo(f:Foo)
val s : String = "bar"
foo(s)

would compile just fine. 会编译的很好。

In the same way, a DI container would be unable to distinguish the two cases you've shown at runtime because there were never two distinct types at compile time. 同样,DI容器将无法区分您在运行时显示的两种情况,因为在编译时从来没有两种不同的类型。

I think that a DI container using Scala reflection and macros could distinguish them (though classOf doesn't make sense in this case), but probably shouldn't: it would violate principle of least surprise rather strongly. 我认为使用Scala反射和宏的DI容器可以区分它们(尽管在这种情况下classOf没有意义),但可能不应该这样:它会强烈违反最小惊讶原则。 Rather more usefully, it can distinguish List[Apple] and List[Orange] despite their classOf being the same. 更有用的是,即使classOf相同,它也可以区分List[Apple]List[Orange]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM