英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论