Hi, i'm having this kind of data class structure: ...
# getting-started
d
Hi, i'm having this kind of data class structure:
Copy code
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
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
Oh so that is about class. How about the diffrence when using with property?
s
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
@Stephan Schroeder so do you mean property is same as method?
s
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
Copy code
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
Copy code
from class A
from class B
https://pl.kotl.in/KSlTMGxch
๐Ÿ™Œ 1
โœ… 1
d
@Stephan Schroeder Thank you for the explain and example.