我想为已经定义的类的伴随对象添加一些扩展函数,比如
fun Toast.Companion.showImageToast(str : String) {
}
我也喜欢在界面上做同样的事情,例如
fun Runnable.Companion.mainHandler() {
}
我已经查阅了文档,只是为用户定义的类中的伴随对象找到定义扩展函数的语法,而不是没有伴随对象的类
我可以在kotlin有机会这样做吗?
答案 0 :(得分:8)
在Kotlin 1.0中,如果某个类没有定义伴随对象,则无法为该伴随对象定义扩展函数。也无法为Java类和接口定义扩展函数,例如- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// *** add support for light weight migration ***
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StoreName.sqlite"];
NSError *error = nil;
// *** Add support for lightweight migration by passing options value ***
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
return _persistentStoreCoordinator;
}
。