简体   繁体   中英

Scala: class type required but T found

I've found similar issues of this particular problem, however the problem was due to someone trying to instantiate T directly. Here I'm trying to create a trait that is a general interface to extend classes and store them automatically in a database such as Riak using classOf[T] . Using Scala 2.10.

Here's my code:

trait RiakWriteable[T] {

  /**
   * bucket name of data in Riak holding class data
   */
  def bucketName: String

  /**
   * determine whether secondary indices will be added
   */
  def enable2i: Boolean

  /**
   * the actual bucket
   */
  val bucket: Bucket = enable2i match {
    case true => DB.client.createBucket(bucketName).enableForSearch().execute()
    case false => DB.client.createBucket(bucketName).disableSearch().execute()
  }

  /**
   * register the scala module for Jackson
   */
  val converter = {
    val c = new JSONConverter[T](classOf[T], bucketName)
    JSONConverter.registerJacksonModule(DefaultScalaModule)
    c
  }

  /**
   * store operation
   */
  def store = bucket.store(this).withConverter(converter).withRetrier(DB.retrier).execute()

  /**
   * fetch operation
   */
  def fetch(id: String): Option[T] = {
    val u = bucket.fetch(id, classOf[T]).withConverter(converter).withRetrier(DB.retrier).r(DB.N_READ).execute()
    u match {
      case null => None
      case _ => Some(u)
    }
  }

}

Compiler error is class type required but T found .

Example usage (pseudo-code):

class Foo

object Foo extends RiakWriteable[Foo]

Foo.store(object)

So I'm guessing that a manifest of T is not being properly defined. Do I need to implicitly define this somewhere?

Thanks!

Here's an intermediary solution, though it leaves out the converter registration (which I may leave permanently for this use case, not sure yet).

/**
 * trait for adding write methods to classes
 */
trait RiakWriteable[T] {

  /**
   * bucket name of data in Riak holding class data
   */
  def bucketName: String

  /**
   * determine whether secondary indices will be added
   */
  def enable2i: Boolean

  /**
   * the actual bucket
   */
  val bucket: Bucket = enable2i match {
    case true => DB.client.createBucket(bucketName).enableForSearch().execute()
    case false => DB.client.createBucket(bucketName).disableSearch().execute()
  }

  /**
   * store operation
   */
  def store(o: T) = bucket.store(o).withRetrier(DB.retrier).execute()

  /**
   * fetch operation
   */
  def fetch(id: String)(implicit m: ClassTag[T]) = {
    val u = bucket.fetch(id, classTag[T].runtimeClass).withRetrier(DB.retrier).r(DB.N_READ).execute()
    u match {
      case null => None
      case _ => Some(u)
    }
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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