does kotlin have its own version of `Cloneable` as...
# announcements
s
does kotlin have its own version of
Cloneable
as i cant find it in the docs nor in the search thing at kotlinlang.org
r
Not sure what
Cloneable
is but every
data class
has a
copy
method
f
you can just use the one from
java.lang
s
Clonable supposidly provides the
.clone()
method in alot of java classes
i cant access java in kotlin-native
and
kotlin.Cloneable
does not exist
f
well java.lang.Cloneable is an empty interface anyway so just create your own I guess
k
You should try to avoid in Java too, it's a mess.
☝️ 4
s
ok
btw, if i have
Copy code
var x = 1
fun a() {
    var y = x
    y = 6
    println(x)
    println(y)
}
a()
shouldnt x be modified such that y and x have the same value?
k
No, that's not how variables work in most programming languages.
You can think of variables as boxes, and
x = y
means "take the value that's in
y
and put it in
x
too". The boxes themselves,
x
and
y
, stay independent.
s
ok, so
y
would obtain the value of
x
and not the reference to
x
itself?
k
Yes.
s
ok
so to implement
clone()
i would do this?
Copy code
fun clone(): LinkedList<T> {
        val tmp = LinkedList<T>()
        tmp.head = head
        return tmp
    }
if so would
Copy code
fun clone(): LinkedList<T> = LinkedList<T>().head = head
also work?
k
Assignments aren't expressions in Kotlin, so the second won't work and wouldn't do what you wanted anyway.
d
he doesn't understand kotlin much, unfortunately - he's been spamming other networks for weeks with the same stuff
k
The first one appears to make a shallow clone, ie. if you mutate the clone the original will change too.
s
so i would need this?
Copy code
val tmp = LinkedList<T>()
        forEach { tmp.append(it!!) }
        return tmp
k
Not sure why you've got the
!!
, but yeah.
s
ok
can lists normally accept null values as valid elements?
eg MutableList<String?>().add(null)
k
They take a type parameter
T
, and users can make it nullable if they want, like in your example
String?
. The list code itself doesn't need to concern itself with nullability.
s
ok