5

I am new to Kotlin. I have an interface containing two method definitions:

fun onSuccess(result: T)
fun onFailure(e: Exception)

Now, in my fragment I have implemented this interface and want to use these methods inside as:

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
     ..................
     ..................
     override fun onSuccess(result: String) {}
     override fun onFailure(e: Exception) {}
}

In java we can use with @override but here I am getting the error 'Modifier 'override' is not applicable to local function'. I am working in kotlin for last 2-3 days and I love it. But some time small issues taking some time to debug.

Pinaki Mukherjee
  • 1,616
  • 3
  • 20
  • 34

1 Answers1

12

You need to implement the interface on your fragment and move the overriding methods outside your onCreateView method.

class MyFragment : Fragment, MyInterface

You can't override methods inside a method. Another option is you can create an object expression demonstrated below

window.addMouseListener(object : MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) {
        // ...
    }

    override fun mouseEntered(e: MouseEvent) {
        // ...
    }
})

https://kotlinlang.org/docs/reference/object-declarations.html

Dom
  • 8,222
  • 2
  • 15
  • 19
  • This works If i declare the method outside. But my question is, if there is a way we can declare methods inside like java. – Pinaki Mukherjee Jun 27 '17 at 01:05
  • 1
    Updated the answer, you can't override methods inside another method in Java but you can create an object expression. – Dom Jun 27 '17 at 01:10