Skip to content

Instantly share code, notes, and snippets.

@miquelbeltran
Created February 26, 2018 09:24
Show Gist options
  • Save miquelbeltran/1654919b97dde91148fdc9492d43ece3 to your computer and use it in GitHub Desktop.
Save miquelbeltran/1654919b97dde91148fdc9492d43ece3 to your computer and use it in GitHub Desktop.
// Sample from http://www.pacoworks.com/2018/02/25/simple-dependency-injection-in-kotlin-part-1/
interface DaoDatabase {
fun query(s: String): Any
}
class User(val id: Int)
interface DaoOperationsSyntax {
val dao: DaoDatabase
fun User.queryUser() =
dao.query("SELECT * from Users where userId = ${this.id}")
}
object DataRepository {
fun DaoOperationsSyntax.getUser(user: User) = user.queryUser()
}
fun main(args: Array<String>) {
val mySyntax = object : DaoOperationsSyntax {
override val dao: DaoDatabase = object : DaoDatabase {
override fun query(s: String): Any = TODO()
}
override fun User.queryUser(): Any {
return "Test"
}
}
println(mySyntax.getUser(User(1))) // prints Test
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment