user12595983
user12595983

Reputation: 147

(Interface, Class) Kotlin: Expecting member declaration

Class Aim: read review point and comment, ensure that point is within 0-5

class LimitedReview(val point:Int, val comment:String):Review {
if (point<0){
    point=0
}
if (point>5){
    point = 5
}
override fun stars(): Int =point
override fun info(): String =comment
}

interface Review{
fun stars():Int
fun info():String
}

Error:(2, 5) Kotlin: Expecting member declaration Error:(2, 17) Kotlin: Conflicting overloads: public final fun (): Unit defined in LimitedReview, public final fun (): Unit defined in LimitedReview Error:(2, 17) Kotlin: Function declaration must have a name

  1. may i know how to change my code?
  2. which topic should i learn to avoid the same error again?

Thanks!

Upvotes: 0

Views: 1031

Answers (1)

zsmb13
zsmb13

Reputation: 89538

The property you have in the primary constructor of the class will assign the value that you call the constructor with to the point property directly, when your class is created, and you can't modify it any more.

Basically, this code:

class LimitedReview(val point: Int)

Is the same as this:

class LimitedReview(point: Int) {
    val point: Int = point // ctor param to property
}

If you want to perform logic before assigning the value to the property, you have to move the property outside the constructor, and initialize it manually.

This can be done in an initializer block, if you have complex logic for it:

class LimitedReview(point: Int) {
    val point: Int

    init {
        if (point < 0) {
            this.point = 0
        } else if (point > 5) {
            this.point = 5
        } else {
            this.point = point
        }
    }
}

Or if you can fit it into a single expression (coerceIn comes in handy here), then inline with the property declaration:

class LimitedReview(point: Int) {
    val point: Int = point.coerceIn(0..5)
}

Upvotes: 1

Related Questions