Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 如何对密封类的成员调用.value_Kotlin_Sealed Class - Fatal编程技术网

Kotlin 如何对密封类的成员调用.value

Kotlin 如何对密封类的成员调用.value,kotlin,sealed-class,Kotlin,Sealed Class,在下面的代码中,我想开发一个我在google上看到的示例。但是当我试着打电话的时候 .value 在android studio中,它从未被认可或定义。 请看一看,让我知道如何解决这个问题 class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView

在下面的代码中,我想开发一个我在google上看到的示例。但是当我试着打电话的时候

.value
在android studio中,它从未被认可或定义。 请看一看,让我知道如何解决这个问题

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var opAdd = Op1.add(5)
    var opSub = Op1.sub(6)
    var opMul = Op1.mul(7)
    var opDiv = Op1.div(8)

    exec(3, opAdd)
    exec(3, opSub)
    exec(3, opMul)
    exec(3, opDiv)
}

fun exec(operand : Int, op : Op1) = when (op) {
    is Op1.add() -> operand + op.value//ERROR
    is Op1.sub -> operand - op.value//ERROR
    is Op1.mul -> operand * op.value
    is Op1.div -> operand / op.value
}

}
密封类

public sealed class Op1 {

class add(val oAdd : Int) : Op1()
class sub(val oSub : Int) : Op1()
class mul(val oMul : Int) : Op1()
class div(val oDiv : Int) : Op1()

}

必须将类和函数定义更改为

fun exec(operand : Int, op : Op1) = when (op) { // op not op::class
    is Op1.add -> operand + op.value
    is Op1.sub -> operand - op.value
    is Op1.mul -> operand * op.value
    is Op1.div -> operand / op.value
}
public sealed class Op1 {

    class add(val value : Int) : Op1() //value not oAdd
    class sub(val value: Int) : Op1()
    class mul(val value: Int) : Op1()
    class div(val value: Int) : Op1()

}

在我发布任务之前。我已经试过你的答案了……还是不起作用。我再次修改了任务。@AmrBakri你有什么问题?