Created
August 1, 2016 15:08
-
-
Save amanurat/d0259b29f29690825fefd15fbecd9d69 to your computer and use it in GitHub Desktop.
Kotlin Generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open class A { | |
} | |
abstract class Adapter<T : A> { | |
abstract fun create(): T | |
abstract fun itemCount(): Int | |
open fun bind(a: T) { | |
} | |
} | |
class AdapterImpl : Adapter<B>() { | |
override fun create(): B = B() | |
override fun bind(a: B) { | |
} | |
override fun itemCount(): Int = 2 | |
} | |
class B : A() { | |
} | |
class View { | |
var adapter: Adapter<A> by Delegates.notNull() //You must use <A>, <out A>, <in A> doesn work, because it excludes A, and bind method becomes unavailable | |
fun use() { | |
var a = adapter.create(); | |
adapter.bind(a) | |
} | |
} | |
class Main{ | |
fun run(){ | |
var view= View() | |
var adapter = AdapterImpl() | |
view.adapter=adapter // Will not compile, since you can't make Adapter Raw type | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open class A { | |
} | |
abstract class Adapter<T : A> { | |
abstract fun create(): T | |
abstract fun itemCount(): Int | |
open fun bind(a: T) { | |
} | |
} | |
class AdapterImpl : Adapter<A>() { //Use A | |
override fun create(): B = B() //Use B since B:A | |
override fun bind(a: A) { // Use A | |
} | |
override fun itemCount(): Int = 2 | |
} | |
class B : A() { | |
} | |
class View { | |
var adapter: Adapter<A> by Delegates.notNull() | |
fun use() { | |
var a = adapter.create(); | |
adapter.bind(a) | |
} | |
} | |
class Main { | |
fun run() { | |
var view = View() | |
var adapter = AdapterImpl() | |
view.adapter = adapter | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment