Scala - 无法从Generic推断类型

时间:2016-11-01 12:11:45

标签: scala

我是Scala的新手,无法正常使用此代码,任何帮助都将不胜感激!这就是我所拥有的

if(isAdded()) {
     motiveAdapter = new QuoteAdapter(getActivity().getApplicationContext(), qItems);
     motiveRecycler.setAdapter(motiveAdapter);       
}

我不明白为什么它不能推断出类型,因为list是List [Int](A),而foldRight的第二个arg是Int(B)。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

Scala编译器需要帮助

此处Scala编译器无法为您推断类型,因为+可以是字符串连接运算符或数字加法运算符。要消除这种混淆,您必须至少提供B作为Int的输出类型。

您需要至少告诉B所属的类型,以帮助编译器知道天气+是字符串连接或数字加法。

告诉编译器什么是B(结果类型)或告诉编译器什么是xy

list.foldRight[Int]( (x, y) => x + y , acc )

代码下方

println(list.foldRight[Int]( (x, y) => x + y , acc ) )

Scala REPL

scala> :paste
// Entering paste mode (ctrl-D to finish)

sealed trait List[+A] {
  def foldRight[B](f: (B, A) => B, acc: B): B = {
    def go(acc: B, list: List[A]): B = list match {
      case Nil => acc
      case Cons(x, xs) => go(f(acc, x), xs)
    }
    go(acc, this)
  }
}

case object Nil extends List[Nothing]
case class Cons[+A](x: A, xs: List[A]) extends List[A]

val list: List[Int] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
val acc: Int = 0

// Exiting paste mode, now interpreting.

defined trait List
defined object Nil
defined class Cons
list: List[Int] = Cons(1,Cons(2,Cons(3,Cons(4,Nil))))
acc: Int = 0

scala> println(list.foldRight[Int]( (x, y) => x + y , acc ) )
10

答案 1 :(得分:0)

在scala中使用lambda函数而不显式指定类型的惯用方法是case

println(list.foldRight({ case (x, y) => x + y }, acc)) 
相关问题