最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - Is there a way to have structured data in data classes with anonymous classes? - Stack Overflow

programmeradmin2浏览0评论

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
)
发布评论

评论列表(0)

  1. 暂无评论