Reputation: 507
I'm learning Kotlin and I've been stuck with this error for a while: I'm trying to define a class propertie heat
based on another propertie spiciness
using a when
statement with the following code
14 class SimpleSpice{
15 var name: String = "curry"
16 var spiciness: String = "mild"
17 var heat: Int = {
18 get(){
19 when (spiciness) {
20 "weak" -> 0
21 "mild" -> 5
22 "strong" -> 10
23 else-> -1
24 }
25 }
26 }
27 }
I'm getting the following error:
Error:(10, 29) Kotlin: Type mismatch: inferred type is () -> Int but Int was expected
Error:(17, 21) Kotlin: Type mismatch: inferred type is () -> ??? but Int was expected
Error:(18, 9) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public inline operator fun <K, V> Map<out ???, ???>.get(key: ???): ??? defined in kotlin.collections
public operator fun MatchGroupCollection.get(name: String): MatchGroup? defined in kotlin.text
Additionally, the get() code is painted red with the following exeption:
Type mismatch: inferred type is () -> ??? but Int was expected. Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public operator fun MatchGroupCollection.get(name: String): MatchGroup? defined in kotlin.text.
Upvotes: 1
Views: 2084
Reputation: 186
Notice, you declared heat
as var
, without specifying setter.
Try this:
class SimpleSpice {
var name: String = "curry"
var spiciness: String = "mild"
val heat: Int
get() {
return when (spiciness) {
"weak" -> 0
"mild" -> 5
"strong" -> 10
else -> -1
}
}
}
Upvotes: 1