无形:镜像编译类类参数的错误

时间:2018-05-10 03:44:25

标签: scala shapeless lenses

我为所有案例类定义了一个基本特征,并打算通过无形镜头更改基本特征中的字段(例如createTime,updateTime)。

基于以下代码。

// LensTest.scala

package demo

import java.sql.Timestamp

import shapeless._

trait BaseEntity {
  def id: Int
  def createTime: Timestamp
  def updateTime: Timestamp
}

case class User(id: Int, name: String, age: Int, createTime: Timestamp, updateTime: Timestamp) extends BaseEntity

object Util {
  val witCreateTime = Witness('createTime)
  type tpeCreateTime = witCreateTime.T

  def updateCreateTime[A](a: A, time: Timestamp)(implicit mkLens: MkFieldLens.Aux[A, tpeCreateTime, Timestamp]): A = {
    val lenCreateTime = mkLens()
    lenCreateTime.set(a)(time)
  }
}

/**
  * LensTest
  *
  */
object LensTest extends App {
  val user = User(1, "Tom", 18, null, null)
  val now = new Timestamp(System.currentTimeMillis())

  def normal_method_call_is_ok(): Unit = {
    println(Util.updateCreateTime(user, now))
  }
  normal_method_call_is_ok()

  // However, in the below `BaseRepo` definition,
  // Compiler gives an compile error:
  //
  //     could not find implicit value for parameter mkLens: shapeless.MkFieldLens.Aux[E,demo.Util.tpeCreateTime,java.sql.Timestamp]
  //
  //
  // Why? And how to fixed it?
}


class BaseRepo[E <: BaseEntity] {
  def beforeUpdate(e: E): E = {
    val now = new Timestamp(System.currentTimeMillis())
    Util.updateCreateTime(e, now)
  }
}

正如我在代码中评论过的那样。我写了一个updateCreateTime函数来实现我的目标。当我在正常功能中调用它时,它可以工作。但是,当我将它放在BaseRepo类(具有类型参数)时,它编译失败。 我不知道为什么会这样,以及如何解决这个问题?任何帮助都会感激不尽。

1 个答案:

答案 0 :(得分:1)

为编译器提供所需内容:

class BaseRepo[E <: BaseEntity] {
  def beforeUpdate(e: E)(implicit in: MkFieldLens.Aux[E, tpeCreateTime, Timestamp]): E = {
    val now = new Timestamp(System.currentTimeMillis())
    Util.updateCreateTime(e, now)
  }
}

object LensTest extends App {
  val user = User(1, "Tom", 18, null, null)
  val now = new Timestamp(System.currentTimeMillis())

  def normal_method_call_is_ok(): Unit = {
    println(Util.updateCreateTime(user, now))
  }
  //normal_method_call_is_ok()

  val _user = new BaseRepo[User]
  println(_user.beforeUpdate(user))
  // However, in the below `BaseRepo` definition,
  // Compiler gives an compile error:
  //
  //     could not find implicit value for parameter mkLens: shapeless.MkFieldLens.Aux[E,demo.Util.tpeCreateTime,java.sql.Timestamp]
  //
  //
  // Why? And how to fixed it?
}

给出:

用户(1,Tom,18,2018-05-10 11:39:50.287,null)