I don't understand why kotlin is so different to o...
# announcements
i
I don't understand why kotlin is so different to others
g
your
vv
is just a local variable
hope you don't expect local variables to be accesable from outside of the class? Otherwisie I'm afraid to ask about "others".
😂 1
i
instance variable, I don't know if there's this concept in kotlin
g
probably you're looking for
Copy code
class C<T>(v:T) {
    val vv = v
}
i
functions in class, they need to visit variables in the class
in python, we call self.var
g
also, the
+
operation in your code is not defined for
T
, so
vv + vv
won't work.
#getting-started
i
T here is Int
m
Not in your add function. There it's just
T
. You probably want this:
Copy code
fun add(x: C<Int>, y: C<Int>): Int {
    return x.vv + y.vv
}
i
yes, that is what I want
but I don't know why T doesn't work here
c
Python is very different from Kotlin when it comes to type-safety. You can do lots of stuff in Python that's not guaranteed to work in all cases and there's no compiler to scream at you that you're doing something unsafe
T
doesn't work there because it could be literally any type. You could invoke
add(C(false), C(false))
i
yeah, but T is made for polymorphic
pass string, sure, it may be error,
c
Sorry, had a bad example, Boolean is a better example here
i
sneaky, string + string is ok
c
You mean it should be an error for strings at runtime?
We don't want that, we want to prevent this at compile-time
We want to avoid functions that only work for selected inputs
It's actually easier this way: If you declare the function properly, you know what types of values are safe to call it with. In Python for instance it's not always obvious what inputs a function actually accepts.
i
ok, what if I don't return x.vv+y.vv, I only return x.vv that's ok?
c
That's okay, exactly
i
but the editor pops up Unit was expected
c
fun <T> justReturn(C<T> c): T { return c.vv }
You need to declare that you want to return a value of type
T
i
I don't understand why function should return only Unit type
c
Using
: T
If you omit that, it defaults to
: Unit
Which is comparable to not returning anything
i
return ?
c
Sorry?
i
how return x.vv
c
fun <T> justReturn(C<T> c): T { return c.vv }
i
ok, one more thing, why I should put a <T> before the function's name
and I must define T in class or interface before I use it in function?
c
It's a type parameter, basically you're saying "this function works for all sorts of types, not only a particular one". Like a template.
Maybe you can have a look at this article to understand generic classes and functions better: https://www.oracle.com/technetwork/articles/java/juneau-generics-2255374.html
It's for Java, but many concepts explained there apply for Kotlin as well
i
ok
g
Have you checked guide Kotlin for Python developers by Khan Academy? It should be helpful for you https://kotlinlang.org/docs/tutorials/kotlin-for-py/introduction.html #getting-started also a good channel for such questions
i
ok