What is the type of a simple object expression?


#1

package Kotlin101.Objects.Expressions

fun main (args : Array<String>){
  val msg = anythingGoes()
  println ("${msg.message}") //this throws error
}

fun anythingGoes() : Any{   return object{   val message : String = "You can use this anytime"   } }

Is there anyway to access the ‘message’ property in above case?


#2

Not until there's support for a dynamic typing type, so you can use runtime reflection/dynamic typing.

For now just create a class

class Foo(val message: String) {}
fun anythingGoes(): Foo {
  return Foo(“You can use this anytime”)
}


#3

An anonymous object has an anonymous type, so you can say this:

``

  val a =  object{
  val message : String = “You can use this anytime”
  }
  println(a.message)

But you can not denote this type (i.e. write it down), so you need to create a named class to return something like that from a function.