-1

in the below code i want to develop an example i saw on the google. but when i try to call

.value

it is never recognised nor defined in 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()

}
Amr Bakri
  • 11
  • 1
  • 3

1 Answers1

1

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

}
Saeed Masoumi
  • 8,746
  • 7
  • 57
  • 76