Anonymous inner class?

Given following class:

trait Foo {
    fun hi(): String
}

class MyClass() {   val foo = InnerFoo()      inner class InnerFoo : Foo {   override fun hi(): String = "hello"   }    }

Is it possible to make the inner class (Foo) anonymous?

class MyClass() {   val foo = inner object: Foo {   //COMPILE ERROR   override fun hi(): String = "hello"   }    }

Hello! If i correctly, understand what you want, then just removing inner word is enough:

trait Foo {
    fun hi(): String
}

class MyClass() {

  val myField = “field”

  val foo = object : Foo {
  override fun hi(): String = “hello, outer field is $myField
  }
}

fun main(args: Array<String>) {
  println(MyClass().foo.hi())
}


Aleksey,

Your example is working, but according to kotlin documentation it shouldn’t.

A class may be marked as inner to be able to access members of outer class. Inner classes carry a reference to an object of an outer class:

The foo class in your example is not marked as “inner”, but it has access to outer class members. Is it a bug or the documentation is outdated?

It's object expression which is more general analogous to java's anonymous inner classes and since it is expression it closures `this` reference, so it's neither bug or outdated documentation. But i think someone from Kotlin team will provide more formal explanation

Although object expressions are compiled into classes, they are not strictly classes from the language point fo view, and the aforementioned extract from the docs does not apply to them

Thanks for the clarificatoin.

Adding on to this original question… Is there a way to reference this inner class from the outer class? For example, in Android I’m trying to create a RecyclerView adapter on the fly like this:

rvItemsList.adapter = object : RecyclerView.Adapter<ViewHolderInnerClass>() {

    inner class ViewHolderInnerClass(view: View) : RecyclerView.ViewHolder(view) {
        var title: TextView = view.findViewById(R.id.title) as TextView
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        return ViewHolderInnerClass( LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
    }

    override fun getItemCount(): Int {
        return itemList.size // Reference to List<String> object outside this anonymous class
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder.title.text =  itemList[position]
    }
}

Of course, this code doesn’t work because Kotlin doesn’t allow referencing the inner class ViewHolderInnerClass the way I did but how would I go about doing it correctly?