Interface Kotlin Example
1/ Create A New Project And Create an array and add some value
package com.example.interfacetest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
val bookList =ArrayList<String>()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bookList.add("Java Book")
bookList.add("Kotlin Book")
bookList.add("Flutter Book")
}
}
2/ Crate an Interface name is BookData
package com.example.interfacetest
interface BookData {
fun myBook(bookName:String)
}
3/ Create a class BookClass
package com.example.interfacetest
class BookClass() {
}
4/ Add parameter and create function
package com.example.interfacetest
class BookClass(val bookList:ArrayList<String>, val bookData: BookData) { // Add Parameter
fun getMyBook( index:Int){ //Create Function
var myBookName= bookList.get(index)
bookData.myBook(myBookName) // Sent Data
}
}
5/ In MainActivity Implement BookData and Override myBook
package com.example.interfacetest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() , BookData{// Implement BookData
override fun onCreate(savedInstanceState: Bundle?) {
val bookList =ArrayList<String>()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bookList.add("Java Book")
bookList.add("Kotlin Book")
bookList.add("Flutter Book")
}
override fun myBook(bookName: String) {// Add Override Function
}
}
package com.example.interfacetest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() , BookData{
override fun onCreate(savedInstanceState: Bundle?) {
val bookList =ArrayList<String>()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bookList.add("Java Book")
bookList.add("Kotlin Book")
bookList.add("Flutter Book")
var bookClass= BookClass(bookList,this)// Send data in to class
bookClass.getMyBook(1) // Call to function
}
override fun myBook(bookName: String) {
Log.d("Output : ",bookName) // Output
}
}