Vivek Modi
02/22/2022, 10:54 PMdata class Product(val value: String? = null, val price: String? = null) {
var priceInLong = price?.toLong()
}
I want to create a min heap where price value will be minimum. I am creating the object but it giving me some kind of error
fun main() {
var queue = PriorityQueue<Long> { p1: Product, p2: Product ->
p1.priceInLong?.let {
p2.priceInLong?.minus(it)
}
}
val list = listOf(
Product("1", "4.83"),
Product("2", "4.53"),
Product("3", "3.54"),
Product("4", "3.66"),
Product("5", "5.16")
)
}
Error
None of the following functions can be called with the arguments supplied.
<init>((MutableCollection<out TypeVariable(E)!>..Collection<TypeVariable(E)!>?)) where E = TypeVariable(E) for constructor PriorityQueue<E : Any!>(c: (MutableCollection<out E!>..Collection<E!>?)) defined in java.util.PriorityQueue
<init>(Comparator<in TypeVariable(E)!>!) where E = TypeVariable(E) for constructor PriorityQueue<E : Any!>(comparator: Comparator<in E!>!) defined in java.util.PriorityQueue
<init>(PriorityQueue<out TypeVariable(E)!>!) where E = TypeVariable(E) for constructor PriorityQueue<E : Any!>(c: PriorityQueue<out E!>!) defined in java.util.PriorityQueue
<init>(SortedSet<out TypeVariable(E)!>!) where E = TypeVariable(E) for constructor PriorityQueue<E : Any!>(c: SortedSet<out E!>!) defined in java.util.PriorityQueue
<init>(Int) where E = TypeVariable(E) for constructor PriorityQueue<E : Any!>(initialCapacity: Int) defined in java.util.PriorityQueue
Vivek Modi
02/22/2022, 10:58 PMVivek Modi
02/22/2022, 10:58 PMWayne Yang
02/23/2022, 1:50 AMinitialCapacity
is missing.
https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#PriorityQueue(int,%20java.util.Comparator)Adrijan Rogan
02/23/2022, 6:17 AMPriorityQueue<Long>
, if you are putting in Product
(presumably)?
Are you sure comparators can return null? You likely need to handle null prices.
I would also advise against using ?.let
, it makes it less readable when using it for control flow.Zun
02/23/2022, 9:36 AMVivek Modi
02/23/2022, 9:43 AMMarcello Galhardo
02/23/2022, 1:51 PMcompareBy
to easily create a comparator (including multi field comparation). For example:
val queue = PriorityQueue<Product>(compareBy { it.priceInLong })
queue += Product("1", "4.83")
// others...
Vivek Modi
02/23/2022, 5:49 PM