从可空对象获取 simpleName

huangapple go评论56阅读模式
英文:

Getting simpleName from nullable object

问题

I am just wanna print the pendingOperation type on the Log. But pendingOperation can be null.
So that i cannot write the like below:

private var pendingOperation: BleOperationType? = null
val operationName = pendingOperation::class.simpleName ?: "unknown operation"

I want to write that statement in the single line. How can do that?

英文:

I am just wanna print the pendingOperation type on the Log. But pendingOperation can be null.
So that i cannot write the like below:

private var pendingOperation: BleOperationType? = null
val operationName = pendingOperation::class.simpleName ?: "unknown operation"

I want to write that statement in the single line. How can do that?

答案1

得分: 2

val nullableObj: Any? = ...
val simpleName = nullableObj?.let { it::class.simpleName }
这里let 是一种作用域函数允许你在非空值上执行一段代码块如果 nullableObj 不为 null就会执行 let 块内的代码并且它引用非空值在代码块中it::class.simpleName 使用 :: 运算符获取非空值的类的简单名称
英文:
val nullableObj: Any? = ...
val simpleName = nullableObj?.let { it::class.simpleName }

Here, let is a scoping function that allows you to execute a block of code on a non-null value. If nullableObj is not null, the code inside the let block is executed and it refers to the non-null value. In the block, it::class.simpleName gets the simple name of the class of the non-null value using the :: operator.

huangapple
  • 本文由 发表于 2023年3月15日 18:22:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定