logos
logos

Reputation: 1

Type mismatch, expected ListBuffer[Any], actual ListBuffer[CustomClass]

I don't understand the title error knowing that for this function :

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

called with these parameters :

myFunction(
  objectList // :ListBuffer[CustomClass],
  customObject // :CustomObject
)

Am i obliged to call function like this :

myFunction(
  objectList.asInstanceOf[ListBuffer[Any]],
  customObject
)

Produces mismatch type error only for ListBuffer parameter. So CustomObject => Any is ok but no ListBuffer[CustomObject] => ListBuffer[Any] ?

Thank you

Upvotes: 0

Views: 502

Answers (4)

Alexey Romanov
Alexey Romanov

Reputation: 170713

If CustomObject and CustomClass are actually supposed to be the same (or CustomObject is a subtype of CustomClass), you may want to change the function to be generic:

def myFunction[A](objectList: ListBuffer[A], object: A) = ...

Otherwise, the issue is that myFunction can put anything into a ListBuffer[Any], but if you pass a ListBuffer[CustomClass], you can only put values of type CustomClass into it. This explains why ListBuffer is invariant.

If myFunction isn't going to put anything into the Buffer, you can just use Seq (or even more general types), which is covariant. You will be able to pass a ListBuffer there because it extends Seq. Generally, it's a good policy to give the most general possible type to method arguments.

Upvotes: 0

logos
logos

Reputation: 1

Mmm, so or this is not the good collection to use and there is a better either I use it badly and must not give it to the function but initialize into the function instead ?

I suppose Seq are covariant because defining function as following, this works :

def myFunction(objectList: Seq[Any], object: Any): Boolean = {...}

Upvotes: 0

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23319

Thats because ListBuffer is invariant so you can't assign ListBuffer[A] to ListBuffer[SuperTypeOfA], the reason for that is ListBuffer is mutable which is unsafe to make Covaraint. https://docs.scala-lang.org/tour/variances.html

Upvotes: 1

Mahesh Chand
Mahesh Chand

Reputation: 3250

You are using parameter name object, which is a keyword in scala.

def myFunction(objectList: ListBuffer[Any], customObject: Any): Boolean = {...}

If you want object as parameter name, use tilt symbol before it.

def myFunction(objectList: ListBuffer[Any], `object`: Any): Boolean = {...}

Other problem is you can't make it Any using asInstanceOf. So, change ListBuffer[Any] to ListBuffer[CustomClass]

def myFunction(objectList: ListBuffer[CustomClass], customObject: Any): Boolean = {...}

Upvotes: 0

Related Questions