我試圖保存用於在Scala中排序序列的參數,以便稍後推遲執行。Scala保存排序函數參數
例如,我想保存(「.value」)排序函數,而不是「list.sortBy(.value)」,並在稍後檢索此排序函數(「_.value」)實際分揀的時間。
如何保存並檢索延遲執行的排序函數參數?下面是一些樣本測試代碼:
class SortTest {
def testSort() = {
val myClass = new MyClass(0)
val list = List (myClass, new MyClass(1), new MyClass(2), new MyClass(3), new MyClass(4))
// Want to sort by value attribute, but don't want to sort right away. Rather
// how do I save the sort function, and retrieve it at a later time for execution?
list.sortBy(_.value)
// save the sort function (i.e. sort by the value attribute of myClass)
// something similar to the following syntax
myClass.setSortFunction (_.value)
// retrieve the sort function and sort the list
list.sortBy(myClass.getSortFunction())
}
class MyClass (d:Int){
val value = d
val sortFunc = null
// what should be the signature of this function ?
def setSortFunction (sortFunc:()) = {
this.sortFunc = sortFunc
}
// what should be the return type of this function?
def getSortFunction() = {
return sortFunc
}
}
}
爲什麼不把這個函數分配給變量?你爲什麼不使用懶惰的集合?你想通過推遲排序來完成什麼? –