Class 在Kotlin处使用get()定义类参数
我正在学习Kotlin,我已经被这个错误困扰了一段时间:我试图基于另一个属性Class 在Kotlin处使用get()定义类参数,class,kotlin,properties,Class,Kotlin,Properties,我正在学习Kotlin,我已经被这个错误困扰了一段时间:我试图基于另一个属性spiciness使用when语句和以下代码定义一个类属性heat 14 class SimpleSpice{ 15 var name: String = "curry" 16 var spiciness: String = "mild" 17 var heat: Int = { 18 get(){ 19 when (spiciness) { 20
spiciness
使用when
语句和以下代码定义一个类属性heat
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 }
我得到以下错误:
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
注意,您将
heat
声明为var
,但没有指定setter
试试这个:
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
}
}
}
移除
get
周围的大括号。Kotlin似乎认为您正在将该变量设置为函数。getter可以挂在变量下面。在等号之后,您需要一个实际的int值。这解决了第一个错误,但是get
仍然是红色的,带有exeptionUnresolved引用。由于接收方类型不匹配,以下候选项均不适用:public operator fun MatchGroupCollection.get(名称:String):MatchGroup?在kotlin.text中定义
它应该是val-heat:Int-get()=when(spiciness){…}
看看文档中的示例,它们工作得很好!!为了正确地执行此操作,我应该在var声明中添加set()方法吗?是的,要声明变量,需要定义setter:set(value){}
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
}
}
}