https://kotlinlang.org logo
#announcements
Title
# announcements
s

Sujit

10/25/2019, 8:00 PM
So, I just realized that with
as?
it does not trigger the
init {}
method, and I'm losing some info here when doing the casting from
Serializable
<http://java.io|java.io>
interface that is setup in
init{} block
. So, I'm wondering if there is a way to invoke the
init {}
when casting with
as?
?
🤔 1
c

Casey Brooks

10/25/2019, 8:05 PM
Do you have a code sample to share? But the
as?
operator doesn’t create any new objects, it just casts it from one type to another, so I wouldn’t expect
init { }
to get called from a cast.
s

Sujit

10/25/2019, 8:08 PM
Yeah, that wouldn't call the
init {}
, and I'm looking to a way to reset those bindings that I do on init to reinitialize in polymorphic situation, where my class has multiple super classes.:
Copy code
@Serializable
class TestObject: Model(), java.io.Serializable {
    init {
        super.setSerializer(serializer())
    }
}
There the
setSerializer
is in
Model
class, that I wanna invoke after the casting happens everytime. Does that makes sense?
In
C++
, I would override a copy constructor for the casting, to do such thing. So, I'm wondering what's kotlin's equivalent? What is guaranteed to be called when
as?
is used to cast to the object type?
b

bbaldino

10/25/2019, 8:24 PM
like casey said, don't think
as?
does anything like that as it doesn't create an instance, just casts it. if you want to create a new instance you'd have to implement your own
clone
method or something, which could work simialr to a c++ copy constructor