是否可以创建final像 String 这样的类的扩展?就像在swift中一样,可以在extensionof中添加其他方法final class。
举个例子 - 我想在String扩展中创建一个方法,它会告诉我String密码的有效长度。
val password : String = mEdtPassword!!.getText().toString()
// how to define haveValidLength method in extension
val isValid : Boolean = password.haveValidLength()
Run Code Online (Sandbox Code Playgroud)
注意 - 该示例只是为了了解 的可用性extension,而不是真实场景。
看看这个简单的扩展函数,我有中缀:
infix fun View.isValidColor(hexColor: String?): Boolean {
var isValid = true
return hexColor?.let {
try {
Color.parseColor(it)
} catch (e: Throwable) {
isValid = false
}
isValid
} ?: false
}
//notice how i have infix the extension meaning brackets are not needed, hopefully making it easier to read.
Run Code Online (Sandbox Code Playgroud)
现在让我们看看用法和我尝试过的:
它不是中缀,它遵循中缀规则:
我究竟做错了什么 ?
既然现在我使用显式对象,为什么会失败?ivLogo 是从 kotlin 合成的 ImageView。
通过使用 LiveData 的最新版本“androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha03”,我使用 LiveData 的新构建块(LiveData + Coroutine)为 ViewModel 中名为“搜索产品”的功能开发了代码使用 Retrofit 执行同步网络调用并相应地更新 ViewModel 中的不同标志(isLoading、isError)。我在“查询”LiveData 上使用 Transforamtions.switchMap,因此只要 UI 中的“查询”发生更改,“搜索产品”代码就会使用 Transformations.switchMap 开始执行。一切正常,除了我想在“查询”LiveData 发生更改时取消之前的改造调用。目前我看不到任何方法来做到这一点。任何帮助,将不胜感激。
class ProductSearchViewModel : ViewModel() {
val completableJob = Job()
private val coroutineScope = CoroutineScope(Dispatchers.IO + completableJob)
// Query Observable Field
val query: MutableLiveData<String> = MutableLiveData()
// IsLoading Observable Field
private val _isLoading = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> = _isLoading
val products: LiveData<List<ProductModel>> = query.switchMap { q ->
liveData(context = coroutineScope.coroutineContext) {
emit(emptyList())
_isLoading.postValue(true)
val service = MyApplication.getRetrofitService()
val response = …Run Code Online (Sandbox Code Playgroud) android kotlin kotlin-extension android-livedata kotlin-coroutines
Kotlin 的惰性委托属性lazy 和lazyFast 之间有什么区别?因为它看起来像相同的代码。
private val key: String by lazy {
if (arguments != null && arguments?.getString(Constants.KEY) != null) {
return@lazy arguments?.getString(Constants.KEY).toString()
} else {
return@lazy ""
}
}
private val key: String by lazyFast {
if (arguments != null && arguments?.getString(Constants.KEY) != null) {
return@lazyFast arguments?.getString(Constants.KEY).toString()
} else {
return@lazyFast ""
}
}
Run Code Online (Sandbox Code Playgroud) 基于类型向类添加函数的惯用方法是什么?以下示例使用List作为类,Type Parameter <T>是列表中的对象类.假设您希望根据类型使用不同的比较器对每个列表进行排序.
data class A(val foo: String)
data class B(val bar: Int)
private val aComparator: Comparator<A> = Comparator { lhs, rhs -> rhs.foo.compareTo(lhs.foo) }
private val bComparator: Comparator<B> = Comparator { lhs, rhs -> rhs.bar.compareTo(lhs.bar) }
fun <T: A> List<T>.sort(): List<T> {
return this.sortedWith<T>(aComparator)
}
fun <T: B> List<T>.sort(): List<T> {
return this.sortedWith<T>(bComparator)
}
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误,指出由于Java的重载规则,两个排序函数具有相同的签名.在Java中,我可能会给它们两个不同的可识别名称,但它作为Kotlin扩展(egasortA()b.sortB())相当丑陋.Kotlin没有向List <B>显示sortA,所以似乎有更好的方法来编写sort()来处理不同对象上的不同比较器.
这个例子非常简单,但想象一下,如果我没有修改类A和B的权限,那么我就无法使用继承或在它们上实现接口.我还考虑过为每个类添加一个比较器并使用Any?但这似乎也很麻烦.
我刚看了Kotlin 标准库,发现了一些奇怪的扩展函数componentN ,其中N是从1到5的索引.
所有类型的基元都有函数.例如:
/**
* Returns 1st *element* from the collection.
*/
@kotlin.internal.InlineOnly
public inline operator fun IntArray.component1(): Int {
return get(0)
}
Run Code Online (Sandbox Code Playgroud)
它对我来说很奇怪.我对开发者的动机很感兴趣.打电话array.component1() 而不是array[0]?
在lombok中,扩展方法obj.method()是一种语法糖SomeUtil.method(obj).它允许为objnull.
Kotlin扩展方法是静态解决的,因此我认为它与我编写时的语法糖相同
fun Any.stringOrNull() = this?.toString()
Run Code Online (Sandbox Code Playgroud)
我收到了关于非空接收器上不必要的安全呼叫的警告.这是否意味着我无法像使用lombok一样调用null对象上的扩展函数?
我想创建一个扩展函数,String该函数需要a String并返回一个String以字符为首的新字符,但按升序排序。我怎样才能做到这一点?我是Kotlin的新手。
我有这个扩展名:
的src/main /科特林/ COM/myproject的/ API/extensions.kt
fun String.asJson() : JsonObject {
return JsonObject.readFrom(this)
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的应用程序时,它工作正常.但是,当我运行使用该扩展函数的测试用例时,它会崩溃:
java.lang.NoSuchMethodError:com.myproject.api.ExtensionsKt.asJson(Ljava/lang/String;)Lcom/eclipsesource/json/JsonObject;
我错过了什么?
在3x3矩阵表示中,我可以找到两个对角线的总和,其中一个衬垫Swift如下,
let array = [
[1, 2, 3],
[4, 5, 6],
[-7, 8, 9]
]
let d1 = array.enumerated().map({ $1[$0] }).reduce(0, +)
let d2 = array.reversed().enumerated().map({ $1[$0] }).reduce(0, +)
print(d1) // prints 15
print(d2) // prints 1
Run Code Online (Sandbox Code Playgroud)
我能找到map和reduce当量Kotlin为flatMap和fold,但未能找到enumerated.
我们如何才能实现与更高阶函数类似Kotlin?