结构化类型以匹配类构造函数

时间:2013-08-26 11:15:38

标签: scala reflection manifest duck-typing

是否可以创建一个结构化类型ins 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)

我相信这可以使用manifest使用runtimeClass和getConstructors,但是我想知道这是否可以使用更干净(通过使用类似结构化类型的东西)

1 个答案:

答案 0 :(得分:4)

考虑使用类型伴侣对象作为函数值,而不是反射或结构类型,

scala> case class UserId(val id: Long) extends AnyVal
defined class UserId

scala> def anotherMethod[T, U](ctor: T => U, t: T) = ctor(t)
anotherMethod: [T, U](ctor: T => U, t: T)U

scala> anotherMethod(UserId, 3L)
res0: UserId = UserId(3)

这适用于案例类,因为Scala编译器会自动为伴随对象提供一个apply方法,该方法调用类主构造函数,并且还会安排同伴扩展相应的{{1}特质。

如果由于某种原因,您的类型不能是案例类,您可以自己提供应用方法,

FunctionN

或者您可以在呼叫站点使用函数文字,

object UserId extends (Long => UserId) {
  def apply(l: Long) = new UserId(l)
}
相关问题