【发布时间】:2013-08-26 11:15:37
【问题描述】:
是否可以在 scala 中创建结构化类型以匹配类构造函数(与类中的方法/函数定义相反)
要正常匹配一个类的方法调用,你可以这样做
type SomeType : {def someMethod:String}
这可以让你做一些像这样的方法
someMethod(a:SomeType) = {
println(a.someMethod)
}
类似这样的东西是什么意思
type AnotherType: {.......}
这将适用于这样的事情
class UserId(val id:Long) extends AnyVal
所以你可以做这样的事情
anotherMethod(a:AnotherType,id:Long):AnotherType = {
new a(id)
}
anotherMethod(UserId,3) // Will return an instance of UserId(3)
我相信使用 runtimeClass 和 getConstructors 使用清单是可能的,但是我想知道这是否可以更干净地使用(通过使用结构化类型之类的东西)
【问题讨论】:
-
不,不可能。
-
嗯,好的,谢谢,所以我想您只需要将反射与清单一起使用?
标签: scala reflection manifest duck-typing