简体   繁体   English

如何在密封类的成员上调用.value

[英]How to call .value on a member of sealed class

in the below code i want to develop an example i saw on the google. 在下面的代码中,我想开发一个我在Google上看到的示例。 but when i try to call 但是当我尝试打电话时

.value

it is never recognised nor defined in android studio. 它在android studio中永远不会被识别或定义。 please have a look and let me know how to fix this issue 请看看,让我知道如何解决此问题

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
}

}

sealed class : 密封类

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()

}

You must change your class and function definitions to 您必须将类和函数定义更改为

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()

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM