0

是否可以在 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使用清单是可能的,但是我想知道这是否可以更干净地使用(通过使用结构化类型之类的东西)

4

1 回答 1

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调用类主构造函数的方法,并且还会安排伴随对象扩展适当的FunctionN特征。

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

object UserId extends (Long => UserId) {
  def apply(l: Long) = new UserId(l)
}

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

anotherMethod(new UserId(_: Long), 3L)
于 2013-08-26T12:38:09.690 回答