https://kotlinlang.org logo
Title
d

dattq2303

09/09/2021, 11:10 AM
Hi, i'm having this kind of data class structure:
abstract class AuthorizeSalesAdditionalSecurity {
    @SerializedName("lang")
    // Using like below is fine too
    // abstract val lang: String
    open val lang: String? = null
    @SerializedName("POSTransactionID")
    // abstract val POSTransactionID: String
    open val POSTransactionID: String? = null
}
data class CreditAuthorizeSalesAdditionalSecurity(
        @SerializedName("lang") override val lang: String,
        @SerializedName("POSTransactionID") override val POSTransactionID: String
) : AuthorizeSalesAdditionalSecurity() {}
data class UnionPayAuthorizeSalesAdditionalSecurity(
        @SerializedName("lang") override val lang: String? = null,
        @SerializedName("POSTransactionID") override val POSTransactionID: String? = null
) : AuthorizeSalesAdditionalSecurity() {}
I realize that I can use keyword "open" or "abstract" in AuthorizeSalesAdditionalSecurity and Kotlin accept both. Can someone explain for me the difference between 2 use case?
m

marstran

09/09/2021, 11:14 AM
An open class can be both instantiated itself, and subclassed. An abstract class can only be subclassed.
You can only create instances from subclasses of an abstract class.
So if it's open, you can do
val a = AuthorizeSalesAdditionalSecurity(lang, POSTransactionID)
. If it's abstract, you cannot do that.
👍 1
d

dattq2303

09/09/2021, 11:17 AM
Oh so that is about class. How about the diffrence when using with property?
s

Stephan Schroeder

09/09/2021, 11:19 AM
open methods can be overwritten (in subclasses), abstract methods (which can only exist in abstract classes) have to be overwritten (in subclasses), since they come without an implementation (like in interfaces).
👀 1
d

dattq2303

09/09/2021, 11:21 AM
@Stephan Schroeder so do you mean property is same as method?
s

Stephan Schroeder

09/09/2021, 11:26 AM
no, i've just never seen open and abstract on properties, so I switched over to methods 😅 But a property in Kotlin isn't a field, it's a getter(and setter if
var
instead of
val
) so it make sense that you can overwrite setters and getters in subclasses.
👍 1
🙌 1
check out
fun main() {
    val listOfA: List<A> = listOf(A(), B())
    
    listOfA.forEach {
        println(it.s)
    }
}

open class A {
    open val s = "from class A"
}

class B: A() {
    override val s get() = "from class B"
}
will output
from class A
from class B
https://pl.kotl.in/KSlTMGxch
1
🙌 1
d

dattq2303

09/09/2021, 11:34 AM
@Stephan Schroeder Thank you for the explain and example.