简体   繁体   English

当伴生对象在类中时使用 .tupled 方法

[英]Using .tupled method when companion object is in class

I am in the process of migrating from Slick to Slick 2, and in Slick 2 you are meant to use the tupled method when projecting onto a case class (as shown here http://slick.typesafe.com/doc/2.0.0-RC1/migration.html )我从油滑迁移到油滑2的过程,并在油滑2,你是为了使用tupled方法投射到一个案件类时(如下图所示http://slick.typesafe.com/doc/2.0.0 -RC1/migration.html )

The problem is when the case class has a companion object, ie if you have something like this问题是当 case 类有一个伴生对象时,即如果你有这样的东西

case class Person(firstName:String, lastName:String) {

}

Along with a companion object与伴生对象一起

object Person {
  def something = "rawr"
}

In the same scope, the tupled method no longer works, because its trying to run tupled on the object , instead of the case class .在同一范围内, tupled方法不再有效,因为它试图在object上运行tupled ,而不是case class

Is there a way to retrieve the case class of Person rather than the object , so you can call tupled properly?有没有办法检索Personcase class而不是object ,以便您可以正确调用tupled

You can also write你也可以写

(Person.apply _).tupled

to avoid repeating the types.以避免重复类型。

This is very similar to what Alexey Romanov said, but in order to avoid lifting apply whenever you need tupled , we just add it to our companion objects.这与 Alexey Romanov 所说的非常相似,但是为了避免在需要tupled时提升apply ,我们只是将它添加到我们的伴生对象中。

object Person {
  def something = "rawr"
  def tupled = (Person.apply _).tupled
}

Now you can call Person.tupled just like you would have if it didn't have a companion object.现在您可以像没有伴随对象一样调用Person.tupled

One workaround is define a companion object as follows:一种解决方法是定义一个伴随对象,如下所示:

object Person extends((String,String) => Person) {
    ...
}

See.看。 https://groups.google.com/d/msg/scala-user/jyWBMz5Qslw/Bryv4ftzRLgJ https://groups.google.com/d/msg/scala-user/jyWBMz5Qslw/Bryv4ftzRLgJ

To build on some of the other comments you could do the following as well since tuple is calling the generated default apply method for the case class.要建立在其他一些评论的基础上,您也可以执行以下操作,因为 tuple 正在为 case 类调用生成的默认应用方法。

object Person {
  ...
  def tupled = (this.apply _).tupled
}

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

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