0

我在伴随对象中定义了两个应用方法PS,假设这可能是语法 desuger,但是当我尝试实例化时PS,显示的错误(代码内联)让我感到困惑:

package tests
import scala.collection.immutable.TreeSet
import scala.collection.immutable.SortedSet



object TestCompanionApply {

  val members = List(2,3,5,7)

  /**
   *  error for the next line:
    type mismatch;  found   : <:<[Nothing,Nothing]  required: A => tests.PH with Ordered[A] 

   */
  val ps1 = PS()


  /**
   * The two errors for the next line: 
   * 
     No implicit view available from Int => tests.PH with Ordered[Int].

     not enough arguments for method apply: (implicit evidence$3: Int => tests.PH with Ordered[Int])tests.PS[Int] in object PS. 
    Unspecified value parameter evidence$3. 

   */
  val ps = PS(members: _*)

}

 class PS[A <% PH with Ordered[A]] 
(val comp : BigInt, val members : SortedSet[A]) {
  def + (a : A) : PS[A] = {
    val h = a.pH
    if (comp % h == 0) {
      this
    } else {
      new PS[A](comp * h, members + a)
    }
  }


  override def hashCode() : Int = comp.hashCode()
  override def equals (o : Any) = o match {
    case a : PS[_] => a.comp == comp
  }

  override def toString = members.toString
}

trait PH {
  def pH : BigInt  
}


object PS {
  def apply[A <% PH with Ordered[A]] () =
    new PS(1, TreeSet[A]())

  def apply[A <% PH with Ordered[A]] (vals : A*) = 
    new PS[A](vals.foldLeft (BigInt(1)) ((ans,v) => ans * v.pH),TreeSet[A]() ++ vals.toList)
}
4

1 回答 1

2

第二个错误表明,没有从Intto的隐式转换test.PH with Ordered[Int]。在这种情况下,您可以简单地自己提供一个隐式转换TestCompanionApply,如下所示:

implicit def intToPH(i: Int) = new PH with Ordered[Int]{
  val pH: BigInt = i
  def compare(that: Int) = pH.toInt - that
}

或者不是隐式地显式地执行它(在右侧使用 Ordered 定义一些新的 PH)。

并且val ps1 = PS()编译器无法推断任何类型参数。我想在你的情况下你可能是指int?因此,通过上述隐式转换,当您定义 ps1 时,您将获得编译成功:

val ps1 = PS[Int]()

但是,我不确定这是否符合您的要求。

于 2013-03-15T19:00:31.123 回答