https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dave08

12/13/2021, 2:47 PM
Lets say I have:
Copy code
interface Foo
class Foo1 : Foo
interface Bar {
   fun <T : Foo> baz(foo: T)
}
// This doesn't work, why? It IS derived from Foo... is there any way to do such a thing w/o taking in a Foo and casting it to Foo1?
class Bar2 {
   override fun baz(foo: Foo1) = TODO()
}
I guess I had to move the type param to the class and it worked... still a bit cryptic why that works and not this...
e

ephemient

12/13/2021, 3:00 PM
Copy code
val bar: Bar
bar.baz(FooNotFoo1()) // legal according to signature, but not according to the Bar2 you wanted to write
d

dave08

12/13/2021, 3:15 PM
But I had
T: Foo
there on the function...?
a

Adam Powell

12/13/2021, 3:46 PM
T : Foo
is not a
Foo1
d

dave08

12/13/2021, 3:47 PM
Oops, I corrected the example... I forgot the inheritence...
The override still doesn't work
a

Adam Powell

12/13/2021, 3:47 PM
Because
T : Foo
is still not a
Foo1
d

dave08

12/13/2021, 3:49 PM
I thought
T : Foo
indicates "a class derived from `Foo`"...?
j

Jacob

12/13/2021, 3:49 PM
to be an override it needs to be able to accept anything the parent can
this method can only accept Foo1
can't accept any other Foo
d

dave08

12/13/2021, 3:49 PM
Oh... why should it be that way?
That particular implementation is only limiting things not expanding them... you can use
override
to limit a return type to not be nullable for example...?
So why not this too?
e

ephemient

12/13/2021, 3:51 PM
limiting output is a subset of super's behavior
d

dave08

12/13/2021, 3:52 PM
And limiting input not?
e

ephemient

12/13/2021, 3:52 PM
limiting input is rejecting some of super's behavior
if Bar2 implements Bar, Bar2 must be usable everywhere a Bar is
a

Adam Powell

12/13/2021, 3:53 PM
you can use 
override
 to limit a return type to not be nullable for example...?
no, you cannot oh, return type, never mind.
d

dave08

12/13/2021, 3:53 PM
Oh... I guess someone that tries using Bar won't succeed if the input is limited, whereas output not...
a

Adam Powell

12/13/2021, 3:54 PM
right
d

dave08

12/13/2021, 3:56 PM
Ok, that's much clearer now... thanks guys 👍🏼! Generics tends to be a bit confusing at times...