Kotlin allows Interface to have code which means a class can implement an Interface, and inherit the behavior from it.
interface FlyingVehicle {
fun startEngine()
}
class AeroPlane : FlyingVehicle {
val engine: Engine = Engine()
override fun startEngine() = engine.start()
}
class Helicopter : FlyingVehicle {
val engine: Engine = Engine()
override fun startEngine() = engine.start()
}
interface FlyingVehicle {
val engine: Engine
fun startEngine() = engine.start()
}
class AeroPlane : FlyingVehicle {
override val engine: Engine = Engine()
}
class Helicopter : FlyingVehicle {
override val engine: Engine = Engine()
}
val aeroPlane = AeroPlane()
val helicopter = Helicopter()
aeroPlane.startEngine()
helicopter.startEngine()
interface SettingToolbarManager {
val toolbar: Toolbar
var toolbarTitle: String
get() = toolbar.title.toString()
set(value) {
toolbar.title = value
}
fun setOnMenuClickListener(onSettingClicked: () -> Unit) {
toolbar.inflateMenu(R.menu.menu_setting)
toolbar.setOnMenuItemClickListener {
when(it.itemId) {
R.id.action_setting -> onSettingClicked()
else -> {}
}
}
}
}
class MainActivity : AppCompatActivity(), SettingToolbarManager {
override val toolbar by lazy { findViewById<Toolbar>(R.id.toolbar) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
toolbarTitle = "My Main Activity"
setOnMenuClickListener {
//Do what you want here
}
}
}
interface ToastManager {
val context: Context
fun shortToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
fun longToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
}
class ToastActivity : AppCompatActivity(), ToastManager {
override val context = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shortToast("This is short toast")
}
}
fun Activity.shortToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
fun Activity.longToast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
class ToastActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
longToast("This is long toast")
}
}
From us to your inbox weekly.