https://kotlinlang.org logo
Title
s

Stefan Peterson

04/29/2019, 6:08 PM
Is there a way to reference
self
or something equivalent in a constructor of a data class such that you could do something like:
abstract class A(abstract name: String?)

data class B(override val name: String? = self::class.simpleName): A()

val b = B()
print(b.name)        // B
s

Shawn

04/29/2019, 6:10 PM
you can still use
this
in this case
are you running into a type mismatch error if you do?
simpleName
is
String?
rather than
String
, so you’ll need a default or
!!
if you like living dangerously
s

Stefan Peterson

04/29/2019, 6:11 PM
Ah whoops left something out of my example, I am implementing an interface and yes you are right about the optional
Updated the code snippet to be more accurate, sorry about that.
s

Shawn

04/29/2019, 6:13 PM
no worries
ahh, you’re running into a different issue
a couple of them actually
you can’t have abstract properties in the constructor
(doing so would make them concrete, not abstract)
abstract class A {
    abstract val name: String?
}

data class B(override val name: String? = this::class.simpleName): A()
is valid
b

bloder

04/29/2019, 6:16 PM
I'm trying using
this
but is showing me that
this is not defined in this context
, are u getting to do that with
this
?
s

Shawn

04/29/2019, 6:17 PM
it’s evaluating just fine in a scratch file, let me double-check in a normal
.kt
lad
ahh, it looks like I am the big dumb -
this
evaluates just fine within the scratch file because it resolves to the outer class that the scratch file code technically resides in
b

bloder

04/29/2019, 6:19 PM
that's weird because I thought in a data class constructor I've already able to use its reference 🤔
s

Shawn

04/29/2019, 6:20 PM
well, sort of, just not through
this
this works:
data class B(override val name: String? = B::class.simpleName): A()
it makes sense that you can’t access
this
within the constructor because an instance hasn’t been instantiated yet
also, just for the record (and those playing along at home), data classes are really not special in almost any regard except for autogenerated methods (
toString()
,
equals()
,
hashCode()
,
copy()
, and property-only constructors). they act just like regular classes in this instance and you should assume they do in most cases
s

Stefan Peterson

04/29/2019, 9:17 PM
Ah yes I had discovers I could do it by doing
B::class.simpleName
was just hoping for something a little nicer. Thanks all. And yea I am using
data class
here specifically for the
copy
feature