android - 阻塞时在Kotlin中调用String方法
问题描述
目前我有一个像这样的 when 块:
val foo = getStringFromBar()
when {
foo == "SOMETHING" -> { /*do stuff*/ }
foo == "SOMETHING ELSE" -> { /*do other stuff*/ }
foo.contains("SUBSTRING") -> { /*do other other stuff*/ }
else -> { /*do last resort stuff*/ }
}
有没有办法把它简化成这样:
val foo = getStringFromBar()
when (foo) {
"SOMETHING" -> { /*do stuff*/ }
"SOMETHING ELSE" -> { /*do other stuff*/ }
.contains("SUBSTRING") -> { /*do other other stuff*/ } // This does not work
else -> { /*do last resort stuff*/ }
}
解决方案
您可以使用with
试试这个方法
with(foo) {
when {
equals("SOMETHING") -> println("Case 1")
equals("something",false) -> println("Case 2")
contains("SUBSTRING") -> println("Case 3")
contains("bar") -> println("Case 4")
startsWith("foo") -> println("Case 5")
else -> println("else Case")
}
}
推荐阅读
- gulp - gulp 4 乙烯基-ftp 无法建立数据连接
- c# - 如何独立使用 Xamarin Profiler 来分析应用程序
- python - 石墨烯 - SqlAlchemy - 抽象属性
- maven-3 - mvn test 没有运行测试类
- angular - 我可以为 Angular 简化这个方法吗?
- ios - 如何更改 NSAttributedString 字体大小
- ruby-on-rails - rails 5 api如何修复验证响应?
- javascript - 如何显示包含颜色代码的对象?
- reactjs - 反应路由:URL 已更改,但组件中的内容未加载
- android - CardView 在我的 android 应用程序中无法正常工作,在屏幕上显示不同