我在伴随对象PS
中定义了两个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)
}
答案 0 :(得分:2)
第二个错误表示没有从Int
到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?因此,使用上面的隐式转换,当您使用:
val ps1 = PS[Int]()
但是我不确定这是否符合你的要求。