我在伴随对象中定义了两个应用方法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)
}