Kotlin从可空值返回空安全值
我有这个功能Kotlin从可空值返回空安全值,kotlin,Kotlin,我有这个功能 fun <T> safe(t: T?): T { return Optional.ofNullable(t).orElseThrow { IllegalStateException("safe value should not be null") } } 但是另一个地方的一些someOtherType是这样声明的: class SomeThirdType(val someOtherType: SomeOtherType) 所以在SomeType中,我有一个函
fun <T> safe(t: T?): T {
return Optional.ofNullable(t).orElseThrow { IllegalStateException("safe value should not be null") }
}
但是另一个地方的一些someOtherType
是这样声明的:
class SomeThirdType(val someOtherType: SomeOtherType)
所以在SomeType
中,我有一个函数:
class SomeType(val someOtherType: SomeOtherType?) {
fun doSomeDamage(): SomeThirdType {
//some work
return SomeThirdType(safe(someOtherType))
}
}
我对
safe
功能不满意,有更好的方法吗?我觉得这里缺少了一些基本的东西Kotlin已经为您提供了处理可空类型的工具。我只会使用范围函数和/或elvis运算符。在您的具体情况下,elvis操作员似乎已经足够了
class SomeType(val someOtherType: SomeOtherType?) {
fun doSomeDamage(): SomeThirdType {
//some work
return SomeThirdType(someOtherType ?: error("someOtherType should not be null"))
}
}
Kotlin已经为您提供了处理可空类型的工具。我只会使用范围函数和/或elvis运算符。在您的具体情况下,elvis操作员似乎已经足够了
class SomeType(val someOtherType: SomeOtherType?) {
fun doSomeDamage(): SomeThirdType {
//some work
return SomeThirdType(someOtherType ?: error("someOtherType should not be null"))
}
}
SomeType
类的“用户”不会期望在简单的doSomeDamage()
函数调用时发生崩溃。SomeType
已完全构建,但doSomeDamage
可能会崩溃。我个人更喜欢:
fun doSomeDamage(someOtherType:someOtherType):SomeThirdType//不带参数构造函数
或者如果SomeOtherType
确实属于SomeType
(我觉得不是这样):
fun doSomeDamage():SomeThirdType?=其他类型?让{…}
SomeType
类的“用户”不会期望在一个简单的doSomeDamage()
函数调用中发生崩溃。SomeType
已完全构建,但doSomeDamage
可能会崩溃。
我个人更喜欢:
fun doSomeDamage(someOtherType:someOtherType):SomeThirdType//不带参数构造函数
或者如果SomeOtherType
确实属于SomeType
(我觉得不是这样):
fun doSomeDamage():SomeThirdType?=其他类型?让{…}
这是否回答了您的问题?是的。但在我的团队中,我们有一个不使用的政策!!是另一种方式吗?我认为你的安全
相当于代码>(除了速度较慢且产生的异常消息稍微不太有用之外)以及所有不使用它的原因都适用。这是否回答了您的问题?是的。但在我的团队中,我们有一个不使用的政策!!是另一种方式吗?我认为你的安全
相当于代码>(除了速度较慢且产生的异常消息稍微不太有用外)以及所有不使用它的原因都适用。谢谢,是的,这也会起作用,但在我看来,使用安全功能更整洁,噪音更小“Kotlin已经为您提供了工具”。的确空值在Kotlin中就不那么可怕了,因为您总是知道它们何时可能出现,并且编译器不会让您做任何不安全的事情。安全调用操作符、elvis操作符和一系列带有可调零接收器的扩展函数使得在可能出现空值时处理空值变得更加容易。不要害怕他们!谢谢,是的,这也会起作用,但使用安全功能更整洁,在我看来“Kotlin已经给你工具了”。的确空值在Kotlin中就不那么可怕了,因为您总是知道它们何时可能出现,并且编译器不会让您做任何不安全的事情。安全调用操作符、elvis操作符和一系列带有可调零接收器的扩展函数使得在可能出现空值时处理空值变得更加容易。不要害怕他们!