0

コンパニオンオブジェクトPSで定義された2つのapplyメソッドがあり、構文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

Int2 番目のエラーは、 からへの暗黙的な変換がないことを示してい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 に答える