Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

None type in Priority queue scala

I'm using a priority queue to order a case class called TreeNodeWithCostAndHeuristic

  case class TreeNodeWithCostAndHeuristic[S,A](parent:Option[TreeNodeWithCostAndHeuristic[S,A]],
                                           action: Option[A],
                                           state: S,
                                           cost: Double,
                                           estimatedRemainingCost: Double)

This priority queue is created inside a function that uses its parameter to set the initial state while the other values have to be kept as None or 0

  def HeuristicGraphSearch[S,A](problem: ProblemWithCostAndHeuristic[S,A]) = {
    val root = TreeNodeWithCostAndHeuristic(parent = None,action=None,state=problem.initialState,cost = 0.0, estimatedRemainingCost = 0.0)
    val frontier : mutable.PriorityQueue[TreeNodeWithCostAndHeuristic[S,A]] = mutable.PriorityQueue.empty[TreeNodeWithCostAndHeuristic[S,A]]
    frontier.enqueue(root)

However because parent and action are none I get a mismatch between expected type TreeNodeWithCostAndHeuristic[S,A] and the one I'm trying to enqueue TreeNodeWithCostAndHeuristic[S,Nothing].

As far as I know Nothing is a subtype of Option and in my case class both parent and action are options. Why am I getting the mismatch?

like image 466
Brandon Avatar asked Apr 11 '26 22:04

Brandon


1 Answers

It's related to the way Scala compiler infers types. Short answer is to simply help it out a bit by explicitly declaring the types when constructing your case class:

val root = TreeNodeWithCostAndHeuristic[S, A](parent = None,action=None,state=problem.initialState,cost = 0.0, estimatedRemainingCost = 0.0)

Reason why TreeNodeWithCostAndHeuristic[S, Nothing] is not considered a valid substitute for TreeNodeWithCostAndHeuristic[S, A] is because it's not its subclass; to be one, it would have to be covariant in type A. If some Foo[A] is covariant in its type A, only then the following holds: Foo[S] <: Foo[A] for any S that is subclass of A.

like image 147
slouc Avatar answered Apr 14 '26 01:04

slouc