我寫了以下測驗:
"List" should "be [3, 4] for condition '_ <= 2'" in {
val l: List[Int] = List(1, 2, 3, 4)
assertResult(List(3, 4))(dropWhile(l, _ <= 2))
}
對于功能:
def dropWhile[A](l: List[A], f: A => Boolean): List[A] = l match {
case Nil => List()
case Cons(h, t) => if (f(h)) dropWhile(t, f) else t
}
但是,我missing parameter type for expanded function在傳遞_ <= 2給時得到dropWhile(l, _ <= 2)。有什么問題?我該如何解決?
uj5u.com熱心網友回復:
問題是型別推斷在Scala 2中的作業方式。那時編譯器還不知道,A因此Int它不知道如何擴展_ <= 2
有多種方法可以解決這個問題。
使用在此獎勵中改進的Scala 3,它應該可以正常作業。
手動指定型別引數:
dropWhile[Int](l, _ <= 2)
// Or
dropWhile(l, (x: Int) => x <= 2)
- (我最喜歡的一個)將函式移動到它自己的引數串列中,以便型別推斷在Scala 2中按預期作業;它還提供了更好的 API 恕我直言。
// Definition site
def dropWhile[A](l: List[A])(f: A => Boolean): List[A] = ???
// Call site
dropWhile(l)(_ <= 2) // Or dropWhile(l)(x => x <= 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/536738.html
上一篇:如何連接前綴相等的表?
下一篇:如何從各個值創建資料框和模式
