admin管理员组

文章数量:1410674

I'd like to be able to do the below (minimal example, not real use-case):

data class Customer(
  name: String,
  address: object {
    street: String,
    city: String
  }
)

Is this currently possible via some syntax?

I'd like to be able to do the below (minimal example, not real use-case):

data class Customer(
  name: String,
  address: object {
    street: String,
    city: String
  }
)

Is this currently possible via some syntax?

Share Improve this question asked Mar 7 at 6:44 RollieRollie 4,7794 gold badges39 silver badges68 bronze badges 4
  • 1 Do you mean something equivalent to C# anonymous types? I don't think Kotlin has such a feature. – k314159 Commented Mar 7 at 14:47
  • 1 You can't do this in a constructor parameter list such as you have in your question, but if you use a normal class you can make one of its properties var address = object : Any() { var street: String }. Not sure how you could use it though. Can you provide a use case? – k314159 Commented Mar 7 at 15:00
  • 1 See also kotlinlang./docs/… – k314159 Commented Mar 7 at 15:02
  • Hello, what is it you're trying to accomplish? In other words, why do you need this? I'd hate to solve for Y, when your problem is X. – Darryl Johnson Commented Mar 9 at 2:07
Add a comment  | 

2 Answers 2

Reset to default 1

Seems like the current answer is unfortunately "you can't". Maybe in the future...

You can achieve that by using by creating two different classes Customer and Address

data class Customer(
    var name: String,
    var address: Address
)
        
data class Address(
    var street: String,
    var city: String
)

and if you want use different classes instead of Address than you can use Any which can hold any type of object

data class Customer(
    var name: String,
    var address: Any
)

本文标签: kotlinIs there a way to have structured data in data classes with anonymous classesStack Overflow