found scala.Int(0) required Int 0

2019-08-12 22:42发布

问题:

I am new to scala, and I am running some exercises from book about to implement a List.

I have a method sum to add all numbers in list. I use TDD approach, so first I just return 0 to make it fail. But the compile complains that type mismatch. It expects Int but received a scala.Int.

def sum[Int](as: MList[Int]): Int = 
{
    0
}

Complain messages:

MList.scala:17: error: type mismatch;
 found   : scala.Int(0)
 required: Int
    0
    ^
one error found

So I try to changed to

def sum[scala.Int](as: MList[scala.Int]): scala.Int = 
{
    0
}

Compiler complains that . should not exist in [scala.Int].

I also tried cast 0 to new Int(0), Int(0), (Int)0, new Int (I come from C++) to match the return type, and it didn't work too.

What's difference between scala.Int(0) and a literal 0? Is that I forget to include some package like built-in number package?

回答1:

The problem is that, here

def sum[Int](as: MList[Int]): Int = 0
       ^^^^^

You're declaring a new type called Int that shadows scala.Int. Your sum method is generic, and Int is the name of its type parameter.

Just remove the type parameter.

def sum(as: MList[Int]): Int = 0


标签: scala