根据可为空值创建可为空对象

发布于 2025-01-16 12:12:57 字数 544 浏览 2 评论 0原文

我必须创建一个具有可为空属性的域类对象。这个创建是原始类的扩展。

例如:

Meeting({required String id, required Datetime date, Example? example})

Example后面的Domainclass是一个像这样的类:Example(String value)

MeetingPrimitive.dart:

extension MeetingPrimitiveX on Meeting {

Meeting toDomain() {
  return Meeting(
    id: id,
    date: date,
    example: example == null ? null : Example(example)
}

}

我的问题是,我如何简化它:

example == null ? null : Example(example)
'''


thanks in advance

i have to create a domain class object which has a nullable attribute. This Creating is in an extansion of a primitive class.

For example: Domainclass

Meeting({required String id, required Datetime date, Example? example})

behind Example is an class like so: Example(String value)

MeetingPrimitive.dart:

extension MeetingPrimitiveX on Meeting {

Meeting toDomain() {
  return Meeting(
    id: id,
    date: date,
    example: example == null ? null : Example(example)
}

}

My question is, how can i simplify this:

example == null ? null : Example(example)
'''


thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想念有你 2025-01-23 12:12:57

一般情况下你不能。
您可以通过各种方式更改它,但没有什么比这里更直接的了。

一种变体是:

extension DoWith<T> on T {
  R doWith<R>(R Function(T) action) => action(this);
}

这样,您可以编写:

 example?.doWith(Example.new)

如果 example 是非 则有条件地调用 Example.new 构造函数(剥离未命名的构造函数) >空。

稍微短一点,需要一个辅助函数,并且......实际上在我看来并不更具可读性。

You generally can't.
You can change it in various ways, but nothing is more direct than what you have here.

One variant would be:

extension DoWith<T> on T {
  R doWith<R>(R Function(T) action) => action(this);
}

With that, you can write:

 example?.doWith(Example.new)

to conditionally call the Example.new constructor (tear-off of the unnamed constructor) if example is non-null.

Slightly shorter, requires a helper function, and ... isn't actually more readable IMO.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文