diff --git a/ant/src/org/jetbrains/kotlin/ant/KotlinAntTaskUtil.kt b/ant/src/org/jetbrains/kotlin/ant/KotlinAntTaskUtil.kt index 5cb8bb49991..e1f8957d3b9 100644 --- a/ant/src/org/jetbrains/kotlin/ant/KotlinAntTaskUtil.kt +++ b/ant/src/org/jetbrains/kotlin/ant/KotlinAntTaskUtil.kt @@ -29,8 +29,8 @@ internal object KotlinAntTaskUtil { private val libPath: File by lazy { // Find path of kotlin-ant.jar in the filesystem and find kotlin-compiler.jar in the same directory - val resourcePath = "/" + javaClass.name.replace('.', '/') + ".class" - val jarConnection = javaClass.getResource(resourcePath).openConnection() as? JarURLConnection + val resourcePath = "/" + this::class.java.name.replace('.', '/') + ".class" + val jarConnection = this::class.java.getResource(resourcePath).openConnection() as? JarURLConnection ?: throw UnsupportedOperationException("Kotlin compiler Ant task should be loaded from the JAR file") val antTaskJarPath = File(jarConnection.jarFileURL.toURI()) @@ -54,7 +54,7 @@ internal object KotlinAntTaskUtil { val cached = classLoaderRef.get() if (cached != null) return cached - val myLoader = javaClass.classLoader + val myLoader = this::class.java.classLoader if (myLoader !is AntClassLoader) return myLoader val classLoader = ClassPreloadingUtils.preloadClasses(listOf(compilerJar), Preloader.DEFAULT_CLASS_NUMBER_ESTIMATE, myLoader, null) diff --git a/build-common/src/org/jetbrains/kotlin/incremental/IncrementalCacheImpl.kt b/build-common/src/org/jetbrains/kotlin/incremental/IncrementalCacheImpl.kt index ee70f2d93ec..0119ff13592 100644 --- a/build-common/src/org/jetbrains/kotlin/incremental/IncrementalCacheImpl.kt +++ b/build-common/src/org/jetbrains/kotlin/incremental/IncrementalCacheImpl.kt @@ -43,7 +43,6 @@ import org.jetbrains.kotlin.serialization.deserialization.TypeTable import org.jetbrains.kotlin.serialization.deserialization.supertypes import org.jetbrains.kotlin.serialization.jvm.BitEncoding import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil -import org.jetbrains.kotlin.utils.singletonOrEmptyList import org.jetbrains.org.objectweb.asm.* import java.io.File import java.security.MessageDigest @@ -272,7 +271,7 @@ open class IncrementalCacheImpl( ProtoBuf.Class::getPropertyList ) + classData.classProto.enumEntryList.map { classData.nameResolver.getString(it.name) } - val companionObjectChanged = createChangeInfo(classFqName.parent(), classFqName.shortName().asString().singletonOrEmptyList()) + val companionObjectChanged = createChangeInfo(classFqName.parent(), listOfNotNull(classFqName.shortName().asString())) val companionObjectMembersChanged = createChangeInfo(classFqName, memberNames) listOf(companionObjectMembersChanged, companionObjectChanged) @@ -780,7 +779,7 @@ sealed class ChangeInfo(val fqName: FqName) { protected open fun toStringProperties(): String = "fqName = $fqName" override fun toString(): String { - return this.javaClass.simpleName + "(${toStringProperties()})" + return this::class.java.simpleName + "(${toStringProperties()})" } } diff --git a/build-common/src/org/jetbrains/kotlin/incremental/LocalFileKotlinClass.kt b/build-common/src/org/jetbrains/kotlin/incremental/LocalFileKotlinClass.kt index 859392686af..2536ff5609e 100644 --- a/build-common/src/org/jetbrains/kotlin/incremental/LocalFileKotlinClass.kt +++ b/build-common/src/org/jetbrains/kotlin/incremental/LocalFileKotlinClass.kt @@ -50,5 +50,5 @@ class LocalFileKotlinClass private constructor( override fun hashCode(): Int = file.hashCode() override fun equals(other: Any?): Boolean = other is LocalFileKotlinClass && file == other.file - override fun toString(): String = "$javaClass: $file" + override fun toString(): String = "${this::class.java}: $file" } diff --git a/build-common/src/org/jetbrains/kotlin/incremental/buildUtil.kt b/build-common/src/org/jetbrains/kotlin/incremental/buildUtil.kt index 312f14c5d1a..2aeed78f95b 100644 --- a/build-common/src/org/jetbrains/kotlin/incremental/buildUtil.kt +++ b/build-common/src/org/jetbrains/kotlin/incremental/buildUtil.kt @@ -145,7 +145,7 @@ fun LookupStorage.update( filesToCompile: Iterable, removedFiles: Iterable ) { - if (lookupTracker !is LookupTrackerImpl) throw AssertionError("Lookup tracker is expected to be LookupTrackerImpl, got ${lookupTracker.javaClass}") + if (lookupTracker !is LookupTrackerImpl) throw AssertionError("Lookup tracker is expected to be LookupTrackerImpl, got ${lookupTracker::class.java}") removeLookupsFrom(filesToCompile.asSequence() + removedFiles.asSequence()) diff --git a/build-common/src/org/jetbrains/kotlin/incremental/storage/BasicMap.kt b/build-common/src/org/jetbrains/kotlin/incremental/storage/BasicMap.kt index aee4d9c6636..f8c0bd0e49e 100644 --- a/build-common/src/org/jetbrains/kotlin/incremental/storage/BasicMap.kt +++ b/build-common/src/org/jetbrains/kotlin/incremental/storage/BasicMap.kt @@ -46,7 +46,7 @@ abstract class BasicMap, V>( fun dump(): String { return with(StringBuilder()) { with(Printer(this)) { - println(this@BasicMap.javaClass.simpleName) + println(this@BasicMap::class.java.simpleName) pushIndent() for (key in storage.keys.sorted()) { diff --git a/build-common/src/org/jetbrains/kotlin/incremental/storage/externalizers.kt b/build-common/src/org/jetbrains/kotlin/incremental/storage/externalizers.kt index e4fe07a65be..4cbe2ee2be9 100644 --- a/build-common/src/org/jetbrains/kotlin/incremental/storage/externalizers.kt +++ b/build-common/src/org/jetbrains/kotlin/incremental/storage/externalizers.kt @@ -131,7 +131,7 @@ object ConstantsMapExternalizer : DataExternalizer> { output.writeByte(Kind.STRING.ordinal) IOUtil.writeString(value, output) } - else -> throw IllegalStateException("Unexpected constant class: ${value.javaClass}") + else -> throw IllegalStateException("Unexpected constant class: ${value::class.java}") } } } diff --git a/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/classFilesComparison.kt b/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/classFilesComparison.kt index 5418d86942f..7b6634b106d 100644 --- a/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/classFilesComparison.kt +++ b/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/classFilesComparison.kt @@ -144,7 +144,7 @@ private fun classFileToString(classFile: File): String { out.write("\n------ string table types proto -----\n${DebugJvmProtoBuf.StringTableTypes.parseDelimitedFrom(input)}") - if (!classHeader!!.metadataVersion.isCompatible()) { + if (!classHeader.metadataVersion.isCompatible()) { error("Incompatible class ($classHeader): $classFile") } diff --git a/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/incrementalModificationUtils.kt b/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/incrementalModificationUtils.kt index 82897c8e116..b22229a730d 100644 --- a/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/incrementalModificationUtils.kt +++ b/build-common/test/org/jetbrains/kotlin/incremental/testingUtils/incrementalModificationUtils.kt @@ -81,8 +81,8 @@ fun getModificationsToPerform( val rules = mapOf Modification>( newSuffix to { path, file -> ModifyContent(path, file) }, - touchSuffix to { path, file -> TouchFile(path, touchPolicy) }, - deleteSuffix to { path, file -> DeleteFile(path) } + touchSuffix to { path, _ -> TouchFile(path, touchPolicy) }, + deleteSuffix to { path, _ -> DeleteFile(path) } ) val modifications = ArrayList() @@ -130,7 +130,7 @@ fun getModificationsToPerform( abstract class Modification(val path: String) { abstract fun perform(workDir: File, mapping: MutableMap) - override fun toString(): String = "${javaClass.simpleName} $path" + override fun toString(): String = "${this::class.java.simpleName} $path" } class ModifyContent(path: String, val dataFile: File) : Modification(path) { diff --git a/compiler/backend-common/src/org/jetbrains/kotlin/backend/common/CodegenUtil.kt b/compiler/backend-common/src/org/jetbrains/kotlin/backend/common/CodegenUtil.kt index bced5c5c8c2..447925759c8 100644 --- a/compiler/backend-common/src/org/jetbrains/kotlin/backend/common/CodegenUtil.kt +++ b/compiler/backend-common/src/org/jetbrains/kotlin/backend/common/CodegenUtil.kt @@ -91,7 +91,7 @@ object CodegenUtil { else if (traitMember is PropertyDescriptor) { for (traitAccessor in traitMember.accessors) { for (inheritedAccessor in (copy as PropertyDescriptor).accessors) { - if (inheritedAccessor.javaClass == traitAccessor.javaClass) { // same accessor kind + if (inheritedAccessor::class.java == traitAccessor::class.java) { // same accessor kind result.put(traitAccessor, inheritedAccessor) } } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/builtinSpecialBridges.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/builtinSpecialBridges.kt index 3347f640d14..5dc175bc30d 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/builtinSpecialBridges.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/builtinSpecialBridges.kt @@ -35,7 +35,6 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getParentCall import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.util.* class BridgeForBuiltinSpecial( @@ -76,7 +75,7 @@ object BuiltinSpecialBridgesUtil { else null val commonBridges = reachableDeclarations.mapTo(LinkedHashSet(), signatureByDescriptor) - commonBridges.removeAll(specialBridgesSignaturesInSuperClass + specialBridge?.from.singletonOrEmptyList()) + commonBridges.removeAll(specialBridgesSignaturesInSuperClass + listOfNotNull(specialBridge?.from)) if (fake) { for (overridden in function.overriddenDescriptors.map { it.original }) { diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineCodegen.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineCodegen.kt index 2151b78ae3e..af2cf12e79e 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineCodegen.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineCodegen.kt @@ -42,7 +42,6 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.addToStdlib.safeAs -import org.jetbrains.kotlin.utils.singletonOrEmptyList import org.jetbrains.org.objectweb.asm.Label import org.jetbrains.org.objectweb.asm.MethodVisitor import org.jetbrains.org.objectweb.asm.Opcodes @@ -289,8 +288,8 @@ class CoroutineCodegen private constructor( } private fun allFunctionParameters() = - originalSuspendFunctionDescriptor.extensionReceiverParameter.singletonOrEmptyList() + - originalSuspendFunctionDescriptor.valueParameters.orEmpty() + listOfNotNull(originalSuspendFunctionDescriptor.extensionReceiverParameter) + + originalSuspendFunctionDescriptor.valueParameters.orEmpty() private fun ParameterDescriptor.getFieldInfoForCoroutineLambdaParameter() = createHiddenFieldInfo(type, COROUTINE_LAMBDA_PARAMETER_PREFIX + (this.safeAs()?.index ?: "")) diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformationClassBuilder.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformationClassBuilder.kt index e657d05996a..630ce80c707 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformationClassBuilder.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformationClassBuilder.kt @@ -294,7 +294,7 @@ class CoroutineTransformerMethodVisitor( get() { assert(suspensionCallEnd.next is LabelNode) { "Next instruction after ${this} should be a label, but " + - "${suspensionCallEnd.next.javaClass}/${suspensionCallEnd.next.opcode} was found" + "${suspensionCallEnd.next::class.java}/${suspensionCallEnd.next.opcode} was found" } return suspensionCallEnd.next as LabelNode diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/refinedIntTypesAnalysis.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/refinedIntTypesAnalysis.kt index bdbc15e956b..088a56b4284 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/refinedIntTypesAnalysis.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/refinedIntTypesAnalysis.kt @@ -217,7 +217,7 @@ private class VarExpectedTypeFrame(maxLocals: Int) : VarFrame): String { val combinedMapping = FileMapping(source, path) realMappings.forEach { fileMapping -> - fileMapping.lineMappings.filter { it.callSiteMarker != null }.forEach { (source, dest, range, callSiteMarker) -> + fileMapping.lineMappings.filter { it.callSiteMarker != null }.forEach { (_, dest, range, callSiteMarker) -> combinedMapping.addRangeMapping(RangeMapping( callSiteMarker!!.lineNumber, dest, range )) diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/IntrinsicArrayConstructors.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/IntrinsicArrayConstructors.kt index a39fa8f4c56..dae87104416 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/IntrinsicArrayConstructors.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/IntrinsicArrayConstructors.kt @@ -28,7 +28,7 @@ internal val classId: ClassId = ClassId.topLevel(FqName("org.jetbrains.kotlin.codegen.intrinsics.IntrinsicArrayConstructorsKt")) internal val bytecode: ByteArray by lazy { - val stream = object {}.javaClass.classLoader.getResourceAsStream("${classId.asString()}.class") + val stream = object {}::class.java.classLoader.getResourceAsStream("${classId.asString()}.class") stream.readBytes().apply { stream.close() } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/boxing/BoxedBasicValue.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/boxing/BoxedBasicValue.kt index cc5146dd65d..7908d4cf5c1 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/boxing/BoxedBasicValue.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/boxing/BoxedBasicValue.kt @@ -20,7 +20,6 @@ import com.intellij.openapi.util.Pair import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.optimization.common.StrictBasicValue import org.jetbrains.kotlin.resolve.jvm.AsmTypes -import org.jetbrains.kotlin.utils.toReadOnlyList import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode import java.util.* diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/StrictBasicValue.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/StrictBasicValue.kt index 8a9d736a7c7..8ef9757f6cd 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/StrictBasicValue.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/StrictBasicValue.kt @@ -52,7 +52,7 @@ open class StrictBasicValue(type: Type?) : BasicValue(type) { override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false if (!super.equals(other)) return false other as StrictBasicValue diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/Util.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/Util.kt index 22b683c03cb..7ba537e155e 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/Util.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/common/Util.kt @@ -182,7 +182,7 @@ fun AbstractInsnNode.isLoadOperation(): Boolean = opcode in Opcodes.ILOAD..Opcod val AbstractInsnNode?.insnText get() = InlineCodegenUtil.getInsnText(this) val AbstractInsnNode?.debugText get() = - if (this == null) "" else "${this.javaClass.simpleName}: $insnText" + if (this == null) "" else "${this::class.java.simpleName}: $insnText" internal inline fun AbstractInsnNode.isInsn(opcode: Int, condition: T.() -> Boolean): Boolean = takeInsnIf(opcode, condition) != null diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt index 087d779b8f9..013a6c35545 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt @@ -113,7 +113,7 @@ class GenerationState @JvmOverloads constructor( } } - val extraJvmDiagnosticsTrace: BindingTrace = DelegatingBindingTrace(bindingContext, "For extra diagnostics in ${this.javaClass}", false) + val extraJvmDiagnosticsTrace: BindingTrace = DelegatingBindingTrace(bindingContext, "For extra diagnostics in ${this::class.java}", false) private val interceptedBuilderFactory: ClassBuilderFactory private var used = false diff --git a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/argumentUtils.kt b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/argumentUtils.kt index 2b8bdc1136f..19235311642 100644 --- a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/argumentUtils.kt +++ b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/argumentUtils.kt @@ -37,23 +37,23 @@ import java.util.* } } -fun copyBean(bean: T) = copyFields(bean, bean.javaClass.newInstance(), true, collectFieldsToCopy(bean.javaClass, false)) +fun copyBean(bean: T) = copyFields(bean, bean::class.java.newInstance(), true, collectFieldsToCopy(bean::class.java, false)) fun mergeBeans(from: From, to: To): To { // TODO: rewrite when updated version of com.intellij.util.xmlb is available on TeamCity - return copyFields(from, XmlSerializerUtil.createCopy(to), false, collectFieldsToCopy(from.javaClass, false)) + return copyFields(from, XmlSerializerUtil.createCopy(to), false, collectFieldsToCopy(from::class.java, false)) } -fun copyInheritedFields(from: From, to: To) = copyFields(from, to, true, collectFieldsToCopy(from.javaClass, true)) +fun copyInheritedFields(from: From, to: To) = copyFields(from, to, true, collectFieldsToCopy(from::class.java, true)) fun copyFieldsSatisfying(from: From, to: To, predicate: (Field) -> Boolean) = - copyFields(from, to, true, collectFieldsToCopy(from.javaClass, false).filter(predicate)) + copyFields(from, to, true, collectFieldsToCopy(from::class.java, false).filter(predicate)) private fun copyFields(from: From, to: To, deepCopyWhenNeeded: Boolean, fieldsToCopy: List): To { if (from == to) return to for (fromField in fieldsToCopy) { - val toField = to.javaClass.getField(fromField.name) + val toField = to::class.java.getField(fromField.name) val fromValue = fromField.get(from) toField.set(to, if (deepCopyWhenNeeded) fromValue?.copyValueIfNeeded() else fromValue) } @@ -72,14 +72,14 @@ private fun Any.copyValueIfNeeded(): Any { is DoubleArray -> Arrays.copyOf(this, size) is BooleanArray -> Arrays.copyOf(this, size) - is Array<*> -> java.lang.reflect.Array.newInstance(javaClass.componentType, size).apply { + is Array<*> -> java.lang.reflect.Array.newInstance(this::class.java.componentType, size).apply { this as Array (this@copyValueIfNeeded as Array).forEachIndexed { i, value -> this[i] = value?.copyValueIfNeeded() } } - is MutableCollection<*> -> (this as Collection).mapTo(javaClass.newInstance() as MutableCollection) { it?.copyValueIfNeeded() } + is MutableCollection<*> -> (this as Collection).mapTo(this::class.java.newInstance() as MutableCollection) { it?.copyValueIfNeeded() } - is MutableMap<*, *> -> (javaClass.newInstance() as MutableMap).apply { + is MutableMap<*, *> -> (this::class.java.newInstance() as MutableMap).apply { for ((k, v) in this@copyValueIfNeeded.entries) { put(k?.copyValueIfNeeded(), v?.copyValueIfNeeded()) } diff --git a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/KotlinJsr223JvmInvocableScriptEngine.kt b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/KotlinJsr223JvmInvocableScriptEngine.kt index e43f5cba55b..75a934ceff4 100644 --- a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/KotlinJsr223JvmInvocableScriptEngine.kt +++ b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/KotlinJsr223JvmInvocableScriptEngine.kt @@ -35,7 +35,7 @@ interface KotlinJsr223JvmInvocableScriptEngine : Invocable { val evalState = state.asState(GenericReplEvaluatorState::class.java) return evalState.history.map { it.item }.filter { it.instance != null }.reversed().ensureNotEmpty("no script ").let { history -> if (receiverInstance != null) { - val receiverKlass = receiverClass ?: receiverInstance.javaClass.kotlin + val receiverKlass = receiverClass ?: receiverInstance::class.java.kotlin val receiverInHistory = history.find { it.instance == receiverInstance } ?: EvalClassWithInstanceAndLoader(receiverKlass, receiverInstance, receiverKlass.java.classLoader, history.first().invokeWrapper) listOf(receiverInHistory) + history.filterNot { it == receiverInHistory } @@ -54,7 +54,7 @@ interface KotlinJsr223JvmInvocableScriptEngine : Invocable { override fun invokeMethod(thiz: Any?, name: String?, vararg args: Any?): Any? { if (name == null) throw java.lang.NullPointerException("method name cannot be null") if (thiz == null) throw IllegalArgumentException("cannot invoke method on the null object") - return invokeImpl(prioritizedHistory(thiz.javaClass.kotlin, thiz), name, args) + return invokeImpl(prioritizedHistory(thiz::class.java.kotlin, thiz), name, args) } private fun invokeImpl(prioritizedCallOrder: List, name: String, args: Array): Any? { diff --git a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/replUtil.kt b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/replUtil.kt index 8b7b83b7d76..928e588814d 100644 --- a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/replUtil.kt +++ b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/repl/replUtil.kt @@ -26,7 +26,7 @@ fun makeScriptBaseName(codeLine: ReplCodeLine) = fun renderReplStackTrace(cause: Throwable, startFromMethodName: String): String { val newTrace = arrayListOf() var skip = true - for ((_, element) in cause.stackTrace.withIndex().reversed()) { + for (element in cause.stackTrace.reversed()) { if ("${element.className}.${element.methodName}" == startFromMethodName) { skip = false } diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/common/output/outputUtils.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/common/output/outputUtils.kt index 8de59aebce7..cf17737907b 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/common/output/outputUtils.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/common/output/outputUtils.kt @@ -34,14 +34,14 @@ fun OutputFileCollection.writeAll(outputDir: File, report: (file: OutputFile, so } } -private val REPORT_NOTHING = { file: OutputFile, sources: List, output: File -> } +private val REPORT_NOTHING: (OutputFile, List, File) -> Unit = { _, _, _ -> } fun OutputFileCollection.writeAllTo(outputDir: File) { writeAll(outputDir, REPORT_NOTHING) } fun OutputFileCollection.writeAll(outputDir: File, messageCollector: MessageCollector) { - writeAll(outputDir) { file, sources, output -> + writeAll(outputDir) { _, sources, output -> messageCollector.report(CompilerMessageSeverity.OUTPUT, OutputMessageUtil.formatOutputMessage(sources, output), CompilerMessageLocation.NO_LOCATION) } } diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/PluginCliParser.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/PluginCliParser.kt index d5ebb3e0fbb..83124909be4 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/PluginCliParser.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/PluginCliParser.kt @@ -35,7 +35,7 @@ object PluginCliParser { ?.map { File(it).toURI().toURL() } ?.toTypedArray() ?: arrayOf(), - javaClass.classLoader + this::class.java.classLoader ) val componentRegistrars = ServiceLoader.load(ComponentRegistrar::class.java, classLoader).toMutableList() diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliLightClassGenerationSupport.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliLightClassGenerationSupport.kt index d9e7cddec66..d9f8051c661 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliLightClassGenerationSupport.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliLightClassGenerationSupport.kt @@ -44,7 +44,6 @@ import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice import org.jetbrains.kotlin.util.slicedMap.WritableSlice -import org.jetbrains.kotlin.utils.emptyOrSingletonList import kotlin.properties.Delegates /** @@ -147,7 +146,7 @@ class CliLightClassGenerationSupport(project: Project) : LightClassGenerationSup val filesForFacade = findFilesForFacade(facadeFqName, scope) if (filesForFacade.isEmpty()) return emptyList() - return emptyOrSingletonList( + return listOfNotNull( KtLightClassForFacade.createForFacade(psiManager, facadeFqName, scope, filesForFacade)) } diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliVirtualFileFinder.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliVirtualFileFinder.kt index 33b1af969fa..d6116923c98 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliVirtualFileFinder.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/CliVirtualFileFinder.kt @@ -26,7 +26,6 @@ import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragment -import org.jetbrains.kotlin.utils.addToStdlib.check import java.io.InputStream class CliVirtualFileFinder( @@ -61,6 +60,6 @@ class CliVirtualFileFinder( private fun findBinaryClass(classId: ClassId, fileName: String): VirtualFile? = index.findClass(classId, acceptedRootTypes = JavaRoot.OnlyBinary) { dir, _ -> - dir.findChild(fileName)?.check(VirtualFile::isValid) - }?.check { it in scope } + dir.findChild(fileName)?.takeIf(VirtualFile::isValid) + }?.takeIf { it in scope } } diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCliJavaFileManagerImpl.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCliJavaFileManagerImpl.kt index 7c71f6c0762..049f4b27329 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCliJavaFileManagerImpl.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCliJavaFileManagerImpl.kt @@ -32,7 +32,6 @@ import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.jvm.KotlinCliJavaFileManager import org.jetbrains.kotlin.util.PerformanceCounter -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* import kotlin.properties.Delegates @@ -50,7 +49,7 @@ class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager) : CoreJ val classNameWithInnerClasses = classId.relativeClassName.asString() index.findClass(classId) { dir, type -> findClassGivenPackage(allScope, dir, classNameWithInnerClasses, type) - }?.check { it.containingFile.virtualFile in searchScope } + }?.takeIf { it.containingFile.virtualFile in searchScope } } } @@ -88,7 +87,7 @@ class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager) : CoreJ override fun findPackage(packageName: String): PsiPackage? { var found = false val packageFqName = packageName.toSafeFqName() ?: return null - index.traverseDirectoriesInPackage(packageFqName) { dir, rootType -> + index.traverseDirectoriesInPackage(packageFqName) { _, _ -> found = true //abort on first found false @@ -149,10 +148,7 @@ class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager) : CoreJ var curClass = topLevelClass while (segments.hasNext()) { val innerClassName = segments.next() - val innerClass = curClass.findInnerClassByName(innerClassName, false) - if (innerClass == null) { - return null - } + val innerClass = curClass.findInnerClassByName(innerClassName, false) ?: return null curClass = innerClass } return curClass diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/index/JvmDependenciesIndexImpl.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/index/JvmDependenciesIndexImpl.kt index 85943c24419..f817df9cee3 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/index/JvmDependenciesIndexImpl.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/index/JvmDependenciesIndexImpl.kt @@ -93,7 +93,7 @@ class JvmDependenciesIndexImpl(_roots: List): JvmDependenciesIndex { ): Set { val result = hashSetOf() traverseDirectoriesInPackage(packageFqName, continueSearch = { - dir, rootType -> + dir, _ -> for (child in dir.children) { if (child.extension != "class" && child.extension != "java") continue diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/GenericReplCompiler.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/GenericReplCompiler.kt index 19677675d47..961a0d4109b 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/GenericReplCompiler.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/GenericReplCompiler.kt @@ -73,7 +73,7 @@ open class GenericReplCompiler(disposable: Disposable, val scriptDescriptor = when (analysisResult) { is ReplCodeAnalyzer.ReplLineAnalysisResult.WithErrors -> return ReplCompileResult.Error(errorHolder.renderedDiagnostics) is ReplCodeAnalyzer.ReplLineAnalysisResult.Successful -> analysisResult.scriptDescriptor - else -> error("Unexpected result ${analysisResult.javaClass}") + else -> error("Unexpected result ${analysisResult::class.java}") } val generationState = GenerationState( diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/ReplInterpreter.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/ReplInterpreter.kt index fe8c503fa2d..4d9e21af05b 100644 --- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/ReplInterpreter.kt +++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/repl/ReplInterpreter.kt @@ -103,7 +103,7 @@ class ReplInterpreter( val scriptDescriptor = when (analysisResult) { is ReplCodeAnalyzer.ReplLineAnalysisResult.WithErrors -> return LineResult.Error.CompileTime(errorHolder.renderedDiagnostics) is ReplCodeAnalyzer.ReplLineAnalysisResult.Successful -> analysisResult.scriptDescriptor - else -> error("Unexpected result ${analysisResult.javaClass}") + else -> error("Unexpected result ${analysisResult::class.java}") } val state = GenerationState( @@ -185,7 +185,7 @@ class ReplInterpreter( private fun renderStackTrace(cause: Throwable, startFromMethodName: String): String { val newTrace = arrayListOf() var skip = true - for ((_, element) in cause.stackTrace.withIndex().reversed()) { + for (element in cause.stackTrace.reversed()) { if ("${element.className}.${element.methodName}" == startFromMethodName) { skip = false } diff --git a/compiler/conditional-preprocessor/src/org.jetbrains.kotlin.preprocessor/Preprocessor.kt b/compiler/conditional-preprocessor/src/org.jetbrains.kotlin.preprocessor/Preprocessor.kt index 8ecde151efb..7cc05d1eee2 100644 --- a/compiler/conditional-preprocessor/src/org.jetbrains.kotlin.preprocessor/Preprocessor.kt +++ b/compiler/conditional-preprocessor/src/org.jetbrains.kotlin.preprocessor/Preprocessor.kt @@ -67,7 +67,7 @@ class Preprocessor(val logger: Logger = SystemOutLogger) { override fun toString(): String = "Modify(${modifications.size})" } - override fun toString() = this.javaClass.simpleName + override fun toString() = this::class.java.simpleName } fun processSources(sourceRoot: File, profile: Profile) { diff --git a/compiler/container/src/org/jetbrains/kotlin/container/Components.kt b/compiler/container/src/org/jetbrains/kotlin/container/Components.kt index 7957cec626d..0f431005938 100644 --- a/compiler/container/src/org/jetbrains/kotlin/container/Components.kt +++ b/compiler/container/src/org/jetbrains/kotlin/container/Components.kt @@ -21,11 +21,11 @@ import java.lang.reflect.* class InstanceComponentDescriptor(val instance: Any) : ComponentDescriptor { override fun getValue(): Any = instance - override fun getRegistrations(): Iterable = instance.javaClass.getInfo().registrations + override fun getRegistrations(): Iterable = instance::class.java.getInfo().registrations override fun getDependencies(context: ValueResolveContext): Collection> = emptyList() override fun toString(): String { - return "Instance: ${instance.javaClass.simpleName}" + return "Instance: ${instance::class.java.simpleName}" } } \ No newline at end of file diff --git a/compiler/container/src/org/jetbrains/kotlin/container/Storage.kt b/compiler/container/src/org/jetbrains/kotlin/container/Storage.kt index 28a440a5ff3..99d85c859a5 100644 --- a/compiler/container/src/org/jetbrains/kotlin/container/Storage.kt +++ b/compiler/container/src/org/jetbrains/kotlin/container/Storage.kt @@ -174,7 +174,7 @@ class ComponentStorage(val myId: String, parent: ComponentStorage?) : ValueResol } private fun injectProperties(instance: Any, context: ValueResolveContext) { - val classInfo = instance.javaClass.getInfo() + val classInfo = instance::class.java.getInfo() classInfo.setterInfos.forEach { (method) -> val methodBinding = method.bindToMethod(context) diff --git a/compiler/daemon/daemon-client/src/org/jetbrains/kotlin/daemon/client/KotlinCompilerClient.kt b/compiler/daemon/daemon-client/src/org/jetbrains/kotlin/daemon/client/KotlinCompilerClient.kt index d464794794e..16cb14ec670 100644 --- a/compiler/daemon/daemon-client/src/org/jetbrains/kotlin/daemon/client/KotlinCompilerClient.kt +++ b/compiler/daemon/daemon-client/src/org/jetbrains/kotlin/daemon/client/KotlinCompilerClient.kt @@ -24,7 +24,6 @@ import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents import org.jetbrains.kotlin.progress.CompilationCanceledStatus -import org.jetbrains.kotlin.utils.addToStdlib.check import java.io.File import java.io.OutputStream import java.io.PrintStream @@ -60,11 +59,11 @@ object KotlinCompilerClient { checkId: Boolean = true ): CompileService? { val flagFile = System.getProperty(COMPILE_DAEMON_CLIENT_ALIVE_PATH_PROPERTY) - ?.let(String::trimQuotes) - ?.check { !it.isBlank() } - ?.let(::File) - ?.check(File::exists) - ?: makeAutodeletingFlagFile(baseDir = File(daemonOptions.runFilesPathOrDefault)) + ?.let(String::trimQuotes) + ?.takeIf { !it.isBlank() } + ?.let(::File) + ?.takeIf(File::exists) + ?: makeAutodeletingFlagFile(baseDir = File(daemonOptions.runFilesPathOrDefault)) return connectToCompileService(compilerId, flagFile, daemonJVMOptions, daemonOptions, reportingTargets, autostart) } diff --git a/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/ClientUtils.kt b/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/ClientUtils.kt index c80f1408c7d..c47d3e53859 100644 --- a/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/ClientUtils.kt +++ b/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/ClientUtils.kt @@ -90,7 +90,7 @@ private inline fun tryConnectToDaemon(port: Int, report: (DaemonReportCategory, when (daemon) { null -> report(DaemonReportCategory.EXCEPTION, "daemon not found") is CompileService -> return daemon - else -> report(DaemonReportCategory.EXCEPTION, "Unable to cast compiler service, actual class received: ${daemon.javaClass.name}") + else -> report(DaemonReportCategory.EXCEPTION, "Unable to cast compiler service, actual class received: ${daemon::class.java.name}") } } catch (e: Throwable) { diff --git a/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/CompileService.kt b/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/CompileService.kt index af8316c7344..148d16b0ac0 100644 --- a/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/CompileService.kt +++ b/compiler/daemon/daemon-common/src/org/jetbrains/kotlin/daemon/common/CompileService.kt @@ -44,22 +44,22 @@ interface CompileService : Remote { class Good(val result: R) : CallResult() { override fun get(): R = result override fun equals(other: Any?): Boolean = other is Good<*> && this.result == other.result - override fun hashCode(): Int = this.javaClass.hashCode() + (result?.hashCode() ?: 1) + override fun hashCode(): Int = this::class.java.hashCode() + (result?.hashCode() ?: 1) } class Ok : CallResult() { override fun get(): Nothing = throw IllegalStateException("Get is inapplicable to Ok call result") override fun equals(other: Any?): Boolean = other is Ok - override fun hashCode(): Int = this.javaClass.hashCode() + 1 // avoiding clash with the hash of class itself + override fun hashCode(): Int = this::class.java.hashCode() + 1 // avoiding clash with the hash of class itself } class Dying : CallResult() { override fun get(): Nothing = throw IllegalStateException("Service is dying") override fun equals(other: Any?): Boolean = other is Dying - override fun hashCode(): Int = this.javaClass.hashCode() + 1 // see comment to Ok.hashCode + override fun hashCode(): Int = this::class.java.hashCode() + 1 // see comment to Ok.hashCode } class Error(val message: String) : CallResult() { override fun get(): Nothing = throw Exception(message) override fun equals(other: Any?): Boolean = other is Error && this.message == other.message - override fun hashCode(): Int = this.javaClass.hashCode() + message.hashCode() + override fun hashCode(): Int = this::class.java.hashCode() + message.hashCode() } val isGood: Boolean get() = this is Good<*> diff --git a/compiler/daemon/src/org/jetbrains/kotlin/daemon/CompileServiceImpl.kt b/compiler/daemon/src/org/jetbrains/kotlin/daemon/CompileServiceImpl.kt index 5a177a8f1fa..5fd0c0b9664 100644 --- a/compiler/daemon/src/org/jetbrains/kotlin/daemon/CompileServiceImpl.kt +++ b/compiler/daemon/src/org/jetbrains/kotlin/daemon/CompileServiceImpl.kt @@ -47,7 +47,6 @@ import org.jetbrains.kotlin.incremental.* import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents import org.jetbrains.kotlin.modules.Module import org.jetbrains.kotlin.progress.CompilationCanceledStatus -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.stackTraceStr import java.io.BufferedOutputStream import java.io.ByteArrayOutputStream @@ -352,7 +351,7 @@ class CompileServiceImpl( } } CompilerMode.NON_INCREMENTAL_COMPILER -> { - doCompile(sessionId, daemonReporter, tracer = null) { eventManger, profiler -> + doCompile(sessionId, daemonReporter, tracer = null) { _, _ -> execCompiler(targetPlatform, Services.EMPTY, k2PlatformArgs, messageCollector) } } @@ -366,7 +365,7 @@ class CompileServiceImpl( val gradleIncrementalServicesFacade = servicesFacade as IncrementalCompilerServicesFacade withIC { - doCompile(sessionId, daemonReporter, tracer = null) { eventManger, profiler -> + doCompile(sessionId, daemonReporter, tracer = null) { _, _ -> execIncrementalCompiler(k2jvmArgs, gradleIncrementalArgs, gradleIncrementalServicesFacade, compilationResults!!, messageCollector, daemonReporter) } @@ -647,7 +646,7 @@ class CompileServiceImpl( ifAlive { - val aliveWithOpts = walkDaemons(File(daemonOptions.runFilesPathOrDefault), compilerId, runFile, filter = { f, p -> p != port }, report = { _, msg -> log.info(msg) }).toList() + val aliveWithOpts = walkDaemons(File(daemonOptions.runFilesPathOrDefault), compilerId, runFile, filter = { _, p -> p != port }, report = { _, msg -> log.info(msg) }).toList() val comparator = compareByDescending(DaemonJVMOptionsMemoryComparator(), { it.jvmOptions }) .thenBy(FileAgeComparator()) { it.runFile } aliveWithOpts.maxWith(comparator)?.let { bestDaemonWithMetadata -> @@ -745,7 +744,7 @@ class CompileServiceImpl( operationsTracer: RemoteOperationsTracer?, body: (PrintStream, EventManager, Profiler) -> ExitCode): CompileService.CallResult = ifAlive { - withValidClientOrSessionProxy(sessionId) { _ -> + withValidClientOrSessionProxy(sessionId) { operationsTracer?.before("compile") val rpcProfiler = if (daemonOptions.reportPerf) WallAndThreadTotalProfiler() else DummyProfiler() val eventManger = EventManagerImpl() @@ -775,7 +774,7 @@ class CompileServiceImpl( tracer: RemoteOperationsTracer?, body: (EventManager, Profiler) -> ExitCode): CompileService.CallResult = ifAlive { - withValidClientOrSessionProxy(sessionId) { _ -> + withValidClientOrSessionProxy(sessionId) { tracer?.before("compile") val rpcProfiler = if (daemonOptions.reportPerf) WallAndThreadTotalProfiler() else DummyProfiler() val eventManger = EventManagerImpl() @@ -907,8 +906,6 @@ class CompileServiceImpl( @JvmName("withValidRepl1") private inline fun withValidRepl(sessionId: Int, body: KotlinJvmReplService.() -> CompileService.CallResult): CompileService.CallResult = withValidClientOrSessionProxy(sessionId) { session -> - (session?.data as? KotlinJvmReplService?)?.let { - it.body() - } ?: CompileService.CallResult.Error("Not a REPL session $sessionId") + (session?.data as? KotlinJvmReplService?)?.body() ?: CompileService.CallResult.Error("Not a REPL session $sessionId") } } diff --git a/compiler/daemon/src/org/jetbrains/kotlin/daemon/KotlinRemoteReplService.kt b/compiler/daemon/src/org/jetbrains/kotlin/daemon/KotlinRemoteReplService.kt index 2d8bf6f1de2..4067c82da4d 100644 --- a/compiler/daemon/src/org/jetbrains/kotlin/daemon/KotlinRemoteReplService.kt +++ b/compiler/daemon/src/org/jetbrains/kotlin/daemon/KotlinRemoteReplService.kt @@ -59,7 +59,7 @@ open class KotlinJvmReplService( } protected fun makeScriptDefinition(templateClasspath: List, templateClassName: String): KotlinScriptDefinition? { - val classloader = URLClassLoader(templateClasspath.map { it.toURI().toURL() }.toTypedArray(), this.javaClass.classLoader) + val classloader = URLClassLoader(templateClasspath.map { it.toURI().toURL() }.toTypedArray(), this::class.java.classLoader) try { val cls = classloader.loadClass(templateClassName) diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/sam/SingleAbstractMethodUtils.kt b/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/sam/SingleAbstractMethodUtils.kt index a25fd2ae229..4ce6358c867 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/sam/SingleAbstractMethodUtils.kt +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/sam/SingleAbstractMethodUtils.kt @@ -21,7 +21,6 @@ import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.replace import org.jetbrains.kotlin.types.typeUtil.asTypeProjection import org.jetbrains.kotlin.types.typeUtil.contains -import org.jetbrains.kotlin.utils.addToStdlib.check // If type 'samType' contains no projection, then it's non-projection parametrization is 'samType' itself // Else each projection type argument 'out/in A_i' (but star projections) is replaced with it's bound 'A_i' @@ -43,7 +42,7 @@ internal fun nonProjectionParametrization(samType: SimpleType): SimpleType? { projection.projectionKind == Variance.INVARIANT -> projection projection.isStarProjection -> - parameter.upperBounds.first().check { + parameter.upperBounds.first().takeIf { t -> !t.contains { it.constructor.declarationDescriptor in parametersSet } }?.asTypeProjection() ?: return@nonProjectionParametrization null diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/structure/impl/JavaClassImpl.kt b/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/structure/impl/JavaClassImpl.kt index 8d8a62bec70..535331d2137 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/structure/impl/JavaClassImpl.kt +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/load/java/structure/impl/JavaClassImpl.kt @@ -111,7 +111,7 @@ class JavaClassImpl(psiClass: PsiClass) : JavaClassifierImpl(psiClass) val psiClass = psi if (psiClass !is KtLightClassMarker) return - val message = "Querying members of JavaClass created for $psiClass of type ${psiClass.javaClass} defined in file ${psiClass.containingFile?.virtualFile?.canonicalPath}" + val message = "Querying members of JavaClass created for $psiClass of type ${psiClass::class.java} defined in file ${psiClass.containingFile?.virtualFile?.canonicalPath}" LOGGER.error(message) } diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/VirtualFileKotlinClass.kt b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/VirtualFileKotlinClass.kt index f8f2d56625c..509fcd49f17 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/VirtualFileKotlinClass.kt +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/VirtualFileKotlinClass.kt @@ -49,7 +49,7 @@ class VirtualFileKotlinClass private constructor( override fun equals(other: Any?) = other is VirtualFileKotlinClass && other.file == file override fun hashCode() = file.hashCode() - override fun toString() = "${javaClass.simpleName}: $file" + override fun toString() = "${this::class.java.simpleName}: $file" companion object Factory { private val LOG = Logger.getInstance(VirtualFileKotlinClass::class.java) diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/incremental/IncrementalPackageFragmentProvider.kt b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/incremental/IncrementalPackageFragmentProvider.kt index 87a92ed4cca..7abaf4fdf40 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/incremental/IncrementalPackageFragmentProvider.kt +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/load/kotlin/incremental/IncrementalPackageFragmentProvider.kt @@ -34,7 +34,6 @@ import org.jetbrains.kotlin.serialization.deserialization.DeserializationCompone import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil import org.jetbrains.kotlin.storage.StorageManager -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import org.jetbrains.kotlin.utils.keysToMap class IncrementalPackageFragmentProvider( @@ -53,7 +52,7 @@ class IncrementalPackageFragmentProvider( override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection = emptySet() override fun getPackageFragments(fqName: FqName): List { - return fqNameToPackageFragment[fqName].singletonOrEmptyList() + return listOfNotNull(fqNameToPackageFragment[fqName]) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt index d83e8427666..5b5f7a069ca 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt @@ -38,7 +38,6 @@ import org.jetbrains.kotlin.resolve.CompilerEnvironment import org.jetbrains.kotlin.resolve.MultiTargetPlatform import org.jetbrains.kotlin.resolve.TargetEnvironment import org.jetbrains.kotlin.resolve.TargetPlatform -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.util.* class ResolverForModule( @@ -179,7 +178,7 @@ abstract class AnalyzerFacade { val resolverForProject = createResolverForProject() fun computeDependencyDescriptors(module: M): List { - val orderedDependencies = firstDependency.singletonOrEmptyList() + module.dependencies() + val orderedDependencies = listOfNotNull(firstDependency) + module.dependencies() val dependenciesDescriptors = orderedDependencies.mapTo(ArrayList()) { dependencyInfo -> resolverForProject.descriptorForModule(dependencyInfo as M) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt index dcb8f7b7f45..16fbf6efcdc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt @@ -113,7 +113,7 @@ class ConstructorConsistencyChecker private constructor( .filterIsInstance() .filter { trace.get(BindingContext.BACKING_FIELD_REQUIRED, it) == true } pseudocode.traverse( - TraversalOrder.FORWARD, variablesData.variableInitializers, { instruction, enterData, exitData -> + TraversalOrder.FORWARD, variablesData.variableInitializers, { instruction, enterData, _ -> fun firstUninitializedNotNullProperty() = propertyDescriptors.firstOrNull { !it.type.isMarkedNullable && !KotlinBuiltIns.isPrimitiveType(it.type) && diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt index bcae261813e..aa11145880f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt @@ -549,7 +549,7 @@ class ControlFlowInformationProvider private constructor( pseudocode.traverse(TraversalOrder.BACKWARD, variableStatusData) { instruction: Instruction, enterData: Map, - exitData: Map -> + _: Map -> val ctxt = VariableUseContext(instruction, reportedDiagnosticMap) val declaredVariables = pseudocodeVariablesData.getDeclaredVariables(instruction.owner, false) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt index 663caeec4c5..d19f0fbd35a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt @@ -1026,7 +1026,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun isBlockInDoWhile(expression: KtBlockExpression): Boolean { - val parent = expression.parent ?: return false + val parent = expression.parent return parent.parent is KtDoWhileExpression } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt index 3afc93e473f..a1b55a822fc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt @@ -17,17 +17,16 @@ package org.jetbrains.kotlin.cfg.pseudocode.instructions import org.jetbrains.kotlin.psi.KtElement -import org.jetbrains.kotlin.utils.emptyOrSingletonList abstract class InstructionWithNext( element: KtElement, blockScope: BlockScope ) : KtElementInstructionImpl(element, blockScope) { var next: Instruction? = null - set(value: Instruction?) { + set(value) { field = outgoingEdgeTo(value) } override val nextInstructions: Collection - get() = emptyOrSingletonList(next) + get() = listOfNotNull(next) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt index 1e863d2765d..26e573862a0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt @@ -22,7 +22,6 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.BlockScope import org.jetbrains.kotlin.cfg.pseudocode.instructions.KtElementInstructionImpl import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction -import org.jetbrains.kotlin.utils.emptyOrSingletonList abstract class AbstractJumpInstruction( element: KtElement, @@ -30,7 +29,7 @@ abstract class AbstractJumpInstruction( blockScope: BlockScope ) : KtElementInstructionImpl(element, blockScope), JumpInstruction { var resolvedTarget: Instruction? = null - set(value: Instruction?) { + set(value) { field = outgoingEdgeTo(value) } @@ -45,5 +44,5 @@ abstract class AbstractJumpInstruction( } override val nextInstructions: Collection - get() = emptyOrSingletonList(resolvedTarget) + get() = listOfNotNull(resolvedTarget) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt index 91e2a34bea6..eae97d42910 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt @@ -24,7 +24,6 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.BlockScope import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor -import org.jetbrains.kotlin.utils.emptyOrSingletonList class ConditionalJumpInstruction( element: KtElement, @@ -37,13 +36,13 @@ class ConditionalJumpInstruction( var nextOnTrue: Instruction get() = _nextOnTrue!! - set(value: Instruction) { + set(value) { _nextOnTrue = outgoingEdgeTo(value) } var nextOnFalse: Instruction get() = _nextOnFalse!! - set(value: Instruction) { + set(value) { _nextOnFalse = outgoingEdgeTo(value) } @@ -51,7 +50,7 @@ class ConditionalJumpInstruction( get() = Arrays.asList(nextOnFalse, nextOnTrue) override val inputValues: List - get() = emptyOrSingletonList(conditionValue) + get() = listOfNotNull(conditionValue) override fun accept(visitor: InstructionVisitor) { visitor.visitConditionalJump(this) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt index 82b140afd6b..743c2fa6fa7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt @@ -27,7 +27,6 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl -import org.jetbrains.kotlin.utils.emptyOrSingletonList class NondeterministicJumpInstruction( element: KtElement, @@ -48,7 +47,7 @@ class NondeterministicJumpInstruction( var next: Instruction get() = _next!! - set(value: Instruction) { + set(value) { _next = outgoingEdgeTo(value) } @@ -60,7 +59,7 @@ class NondeterministicJumpInstruction( } override val inputValues: List - get() = emptyOrSingletonList(inputValue) + get() = listOfNotNull(inputValue) override fun accept(visitor: InstructionVisitor) { visitor.visitNondeterministicJump(this) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt index 63b24b825b0..270afbe0dff 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt @@ -20,7 +20,6 @@ import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.addToStdlib.singletonList sealed class LocalVariableAccessorDescriptor( final override val correspondingVariable: LocalVariableDescriptor, @@ -38,7 +37,7 @@ sealed class LocalVariableAccessorDescriptor( init { val valueParameters = - if (isGetter) emptyList() else createValueParameter(Name.identifier("value"), correspondingVariable.type).singletonList() + if (isGetter) emptyList() else listOf(createValueParameter(Name.identifier("value"), correspondingVariable.type)) initialize(null, null, emptyList(), valueParameters, correspondingVariable.type, Modality.FINAL, Visibilities.LOCAL) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt index 47948b588fb..e7bfd5df06c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/PositioningStrategies.kt @@ -276,7 +276,7 @@ object PositioningStrategies { is KtPropertyAccessor -> element.namePlaceholder is KtAnonymousInitializer -> element else -> throw IllegalArgumentException( - "Can't find text range for element '${element.javaClass.canonicalName}' with the text '${element.text}'") + "Can't find text range for element '${element::class.java.canonicalName}' with the text '${element.text}'") } return markElement(elementToMark) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt index b05ea75c763..c946cc5625f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt @@ -59,7 +59,7 @@ sealed class RenderingContext { is DiagnosticWithParameters1<*, *> -> listOf(d.a) is DiagnosticWithParameters2<*, *, *> -> listOf(d.a, d.b) is DiagnosticWithParameters3<*, *, *, *> -> listOf(d.a, d.b, d.c) - is ParametrizedDiagnostic<*> -> error("Unexpected diagnostic: ${d.javaClass}") + is ParametrizedDiagnostic<*> -> error("Unexpected diagnostic: ${d::class.java}") else -> listOf() } return Impl(parameters) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/adaptiveClassifierNamePolicy.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/adaptiveClassifierNamePolicy.kt index 046e8ebeda7..3fea1bf52fb 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/adaptiveClassifierNamePolicy.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/adaptiveClassifierNamePolicy.kt @@ -46,7 +46,7 @@ private class AdaptiveClassifierNamePolicy(private val ambiguousNames: List error("Unexpected classifier: ${classifier.javaClass}") + else -> error("Unexpected classifier: ${classifier::class.java}") } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt index aec3519bb5c..ab3afa5575b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt @@ -40,7 +40,7 @@ fun KtElement.getDebugText(): String { private object DebugTextBuildingVisitor : KtVisitor() { - private val LOG = Logger.getInstance(this.javaClass) + private val LOG = Logger.getInstance(this::class.java) override fun visitKtFile(file: KtFile, data: Unit?): String? { return "STUB file: ${file.name}" @@ -48,7 +48,7 @@ private object DebugTextBuildingVisitor : KtVisitor() { override fun visitKtElement(element: KtElement, data: Unit?): String? { if (element is KtElementImplStub<*>) { - LOG.error("getDebugText() is not defined for ${element.javaClass}") + LOG.error("getDebugText() is not defined for ${element::class.java}") } return element.text } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt index 210183409f7..5a44bb3ad00 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt @@ -84,7 +84,7 @@ abstract class KtClassOrObject : return getOrCreateBody().addBefore(declaration, anchorAfter) as T } - fun isTopLevel(): Boolean = stub?.isTopLevel() ?: (parent == null || parent is KtFile) + fun isTopLevel(): Boolean = stub?.isTopLevel() ?: (parent is KtFile) override fun isLocal(): Boolean = stub?.isLocal() ?: KtPsiUtil.isLocal(this) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt index bd5fba41b4a..7d80ef440c8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt @@ -28,7 +28,6 @@ import com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* abstract class KtCodeFragment( @@ -175,7 +174,7 @@ abstract class KtCodeFragment( private fun initImports(imports: String?) { if (imports != null && !imports.isEmpty()) { - val importsWithPrefix = imports.split(IMPORT_SEPARATOR).map { it.check { it.startsWith("import ") } ?: "import ${it.trim()}" } + val importsWithPrefix = imports.split(IMPORT_SEPARATOR).map { it.takeIf { it.startsWith("import ") } ?: "import ${it.trim()}" } importsWithPrefix.forEach { addImport(it) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/createByPattern.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/createByPattern.kt index 34debb8093c..91e09b17813 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/createByPattern.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/createByPattern.kt @@ -97,7 +97,7 @@ private val SUPPORTED_ARGUMENT_TYPES = listOf( fun createByPattern(pattern: String, vararg args: Any, factory: (String) -> TElement): TElement { val argumentTypes = args.map { arg -> SUPPORTED_ARGUMENT_TYPES.firstOrNull { it.klass.isInstance(arg) } - ?: throw IllegalArgumentException("Unsupported argument type: ${arg.javaClass}, should be one of: ${SUPPORTED_ARGUMENT_TYPES.map { it.klass.simpleName }.joinToString()}") + ?: throw IllegalArgumentException("Unsupported argument type: ${arg::class.java}, should be one of: ${SUPPORTED_ARGUMENT_TYPES.map { it.klass.simpleName }.joinToString()}") } // convert arguments that can be converted into plain text @@ -105,7 +105,7 @@ fun createByPattern(pattern: String, vararg args: Any, fa val args = args.zip(argumentTypes).map { val (arg, type) = it if (type is PlainTextArgumentType) - (type.toPlainText as Function1).invoke(arg) // TODO: see KT-7833 + (type.toPlainText as Function1).invoke(arg) // TODO: see KT-7833 else arg } @@ -127,7 +127,7 @@ fun createByPattern(pattern: String, vararg args: Any, fa if (arg is String) continue // already in the text val expectedElementType = (argumentTypes[n] as PsiElementPlaceholderArgumentType<*, *>).placeholderClass - for ((range, text) in placeholders) { + for ((range, _) in placeholders) { val token = resultElement.findElementAt(range.startOffset)!! for (element in token.parentsWithSelf) { val elementRange = element.textRange.shiftRight(-start) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/ktElementUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/ktElementUtils.kt index 3dfe1b807ca..0a701a2b903 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/ktElementUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/ktElementUtils.kt @@ -28,5 +28,5 @@ internal fun KtElement.deleteSemicolon() { if (sibling == null || sibling.node.elementType != KtTokens.SEMICOLON) return val lastSiblingToDelete = PsiTreeUtil.skipSiblingsForward(sibling, PsiWhiteSpace::class.java)?.prevSibling ?: sibling - parent?.deleteChildRange(nextSibling, lastSiblingToDelete) + parent.deleteChildRange(nextSibling, lastSiblingToDelete) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/ktPsiUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/ktPsiUtil.kt index 5ab29357877..5a4c68e58e3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/ktPsiUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/ktPsiUtil.kt @@ -219,7 +219,7 @@ fun StubBasedPsiElementBase>.ge } } - require(this is KtClassOrObject) { "it should be ${KtClassOrObject::class} but it is a ${this.javaClass.name}" } + require(this is KtClassOrObject) { "it should be ${KtClassOrObject::class} but it is a ${this::class.java.name}" } val stub = stub if (stub != null) { @@ -339,12 +339,12 @@ fun KtModifierListOwner.isProtected(): Boolean = hasModifier(KtTokens.PROTECTED_ fun KtSimpleNameExpression.isImportDirectiveExpression(): Boolean { val parent = parent - return parent is KtImportDirective || parent?.parent is KtImportDirective + return parent is KtImportDirective || parent.parent is KtImportDirective } fun KtSimpleNameExpression.isPackageDirectiveExpression(): Boolean { val parent = parent - return parent is KtPackageDirective || parent?.parent is KtPackageDirective + return parent is KtPackageDirective || parent.parent is KtPackageDirective } fun KtExpression.isInImportDirective(): Boolean { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinStubBaseImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinStubBaseImpl.kt index 0e7c1f9887f..6255fb6e1b8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinStubBaseImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinStubBaseImpl.kt @@ -33,7 +33,7 @@ val STUB_TO_STRING_PREFIX = "KotlinStub$" open class KotlinStubBaseImpl>(parent: StubElement<*>?, elementType: IStubElementType<*, *>) : StubBase(parent, elementType) { override fun toString(): String { - val stubInterface = this.javaClass.interfaces.filter { it.name.contains("Stub") }.single() + val stubInterface = this::class.java.interfaces.filter { it.name.contains("Stub") }.single() val propertiesValues = renderPropertyValues(stubInterface) if (propertiesValues.isEmpty()) { return "$STUB_TO_STRING_PREFIX$stubType" diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/synthetics/SyntheticClassOrObjectDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/synthetics/SyntheticClassOrObjectDescriptor.kt index 28976a1afa9..6f5973d2b8f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/synthetics/SyntheticClassOrObjectDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/synthetics/SyntheticClassOrObjectDescriptor.kt @@ -86,7 +86,7 @@ class SyntheticClassOrObjectDescriptor( override fun getSealedSubclasses() = emptyList() init { - assert(modality != Modality.SEALED) { "Implement getSealedSubclasses() for this class: $javaClass" } + assert(modality != Modality.SEALED) { "Implement getSealedSubclasses() for this class: ${this::class.java}" } } override fun getDeclaredCallableMembers(): List = diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AllUnderImportScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AllUnderImportScope.kt index 42843e9a371..3b10757fa18 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AllUnderImportScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AllUnderImportScope.kt @@ -79,7 +79,7 @@ class AllUnderImportScope( } override fun printStructure(p: Printer) { - p.println(javaClass.simpleName) + p.println(this::class.java.simpleName) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolveCache.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolveCache.kt index 600bf1ac68c..398d4a72956 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolveCache.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/BodyResolveCache.kt @@ -19,7 +19,7 @@ package org.jetbrains.kotlin.resolve import org.jetbrains.kotlin.psi.KtNamedFunction interface BodyResolveCache { - open fun resolveFunctionBody(function: KtNamedFunction): BindingContext + fun resolveFunctionBody(function: KtNamedFunction): BindingContext object ThrowException : BodyResolveCache { override fun resolveFunctionBody(function: KtNamedFunction): BindingContext { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt index 9bdac74dc69..e11a3c8cad3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt @@ -34,13 +34,11 @@ import org.jetbrains.kotlin.resolve.BindingContext.* import org.jetbrains.kotlin.resolve.DescriptorUtils.classCanHaveAbstractMembers import org.jetbrains.kotlin.resolve.DescriptorUtils.classCanHaveOpenMembers import org.jetbrains.kotlin.resolve.calls.results.TypeSpecificityComparator -import org.jetbrains.kotlin.resolve.descriptorUtil.hasDefaultValue import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.* -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* internal class DeclarationsCheckerBuilder( @@ -189,7 +187,7 @@ class DeclarationsChecker( private fun getUsedTypeAliasParameters(type: KotlinType, typeAlias: TypeAliasDescriptor): Set = type.constituentTypes().mapNotNullTo(HashSet()) { val descriptor = it.constructor.declarationDescriptor as? TypeParameterDescriptor - descriptor?.check { it.containingDeclaration == typeAlias } + descriptor?.takeIf { it.containingDeclaration == typeAlias } } private class TypeAliasDeclarationCheckingReportStrategy( @@ -271,10 +269,10 @@ class DeclarationsChecker( if (visibilityModifier != null && visibilityModifier.node?.elementType != KtTokens.PRIVATE_KEYWORD) { val classDescriptor = constructorDescriptor.containingDeclaration if (classDescriptor.kind == ClassKind.ENUM_CLASS) { - trace.report(NON_PRIVATE_CONSTRUCTOR_IN_ENUM.on(visibilityModifier)); + trace.report(NON_PRIVATE_CONSTRUCTOR_IN_ENUM.on(visibilityModifier)) } else if (classDescriptor.modality == Modality.SEALED) { - trace.report(NON_PRIVATE_CONSTRUCTOR_IN_SEALED.on(visibilityModifier)); + trace.report(NON_PRIVATE_CONSTRUCTOR_IN_SEALED.on(visibilityModifier)) } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt index 43f66aee1e8..a4c7c02aa86 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt @@ -26,7 +26,6 @@ import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.check class LazyExplicitImportScope( private val packageOrClassDescriptor: DeclarationDescriptor, @@ -68,7 +67,7 @@ class LazyExplicitImportScope( } override fun printStructure(p: Printer) { - p.println(javaClass.simpleName, ": ", aliasName) + p.println(this::class.java.simpleName, ": ", aliasName) } // should be called only once @@ -113,5 +112,5 @@ class LazyExplicitImportScope( private fun Collection.choseOnlyVisibleOrAll() = filter { isVisible(it, packageFragmentForVisibilityCheck, position = QualifierPosition.IMPORT) }. - check { it.isNotEmpty() } ?: this + takeIf { it.isNotEmpty() } ?: this } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt index d33bcb3a087..fb963e462f2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt @@ -26,7 +26,6 @@ import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.calls.tower.getTypeAliasConstructors import org.jetbrains.kotlin.resolve.scopes.MemberScope -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.util.* class OverloadResolver( @@ -38,7 +37,7 @@ class OverloadResolver( fun checkOverloads(c: BodiesResolveContext) { val inClasses = findConstructorsInNestedClassesAndTypeAliases(c) - for ((key, value) in c.declaredClasses) { + for (value in c.declaredClasses.values) { checkOverloadsInClass(value, inClasses.get(value)) } checkOverloadsInPackages(c) @@ -115,7 +114,7 @@ class OverloadResolver( scope, name -> val variables = scope.getContributedVariables(name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) val classifier = scope.getContributedClassifier(name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) - variables + classifier.singletonOrEmptyList() + variables + listOfNotNull(classifier) } return packageMembersByName @@ -215,7 +214,7 @@ class OverloadResolver( val bySourceFile = members.groupBy { DescriptorUtils.getContainingSourceFile(it) } var hasGroupIncludingNonPrivateMembers = false - for ((sourceFile, membersInFile) in bySourceFile) { + for (membersInFile in bySourceFile.values) { // File member groups are interesting in redeclaration check if at least one file member is private. if (membersInFile.any { it.isPrivate() }) { hasGroupIncludingNonPrivateMembers = true diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt index 671badeaec4..c710e815fb2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt @@ -37,7 +37,6 @@ import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext import org.jetbrains.kotlin.types.expressions.isWithoutValueArguments -import org.jetbrains.kotlin.utils.addToStdlib.check class QualifiedExpressionResolver { fun resolvePackageHeader( @@ -418,12 +417,12 @@ class QualifiedExpressionResolver { val qualifierDescriptor = when (receiver) { is PackageQualifier -> { val childPackageFQN = receiver.descriptor.fqName.child(name) - receiver.descriptor.module.getPackage(childPackageFQN).check { !it.isEmpty() } ?: + receiver.descriptor.module.getPackage(childPackageFQN).takeIf { !it.isEmpty() } ?: receiver.descriptor.memberScope.getContributedClassifier(name, location) } is ClassQualifier -> receiver.staticScope.getContributedClassifier(name, location) null -> context.scope.findClassifier(name, location) ?: - context.scope.ownerDescriptor.module.getPackage(FqName.ROOT.child(name)).check { !it.isEmpty() } + context.scope.ownerDescriptor.module.getPackage(FqName.ROOT.child(name)).takeIf { !it.isEmpty() } is ReceiverValue -> receiver.type.memberScope.memberScopeAsImportingScope().findClassifier(name, location) else -> null } @@ -549,7 +548,7 @@ class QualifiedExpressionResolver { trace: BindingTrace, position: QualifierPosition ) { - path.foldRight(packageView) { (name, expression), currentView -> + path.foldRight(packageView) { (_, expression), currentView -> storeResult(trace, expression, currentView, shouldBeVisibleFrom = null, position = position) currentView.containingDeclaration ?: error("Containing Declaration must be not null for package with fqName: ${currentView.fqName}, " + diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt index 4f6b72eae00..4b2ef9a5103 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt @@ -121,7 +121,7 @@ abstract class PlatformConfigurator( abstract fun configureModuleComponents(container: StorageComponentContainer) - val platformSpecificContainer = composeContainer(this.javaClass.simpleName) { + val platformSpecificContainer = composeContainer(this::class.java.simpleName) { useInstance(dynamicTypesSettings) declarationCheckers.forEach { useInstance(it) } callCheckers.forEach { useInstance(it) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt index fc2971bcdc4..ebd12116da1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt @@ -281,7 +281,7 @@ class TypeResolver( override fun getVisibility() = Visibilities.LOCAL override fun substitute(substitutor: TypeSubstitutor): VariableDescriptor? { - throw UnsupportedOperationException("Should not be called for descriptor of type $javaClass") + throw UnsupportedOperationException("Should not be called for descriptor of type ${this::class.java}") } override fun isVar() = false @@ -415,7 +415,7 @@ class TypeResolver( } is ClassDescriptor -> resolveTypeForClass(c, annotations, descriptor, element, qualifierResolutionResult) is TypeAliasDescriptor -> resolveTypeForTypeAlias(c, annotations, descriptor, element, qualifierResolutionResult) - else -> error("Unexpected classifier type: ${descriptor.javaClass}") + else -> error("Unexpected classifier type: ${descriptor::class.java}") } } @@ -727,7 +727,7 @@ class TypeResolver( Math.min(classifierChainLastIndex + 1, reversedQualifierParts.size), reversedQualifierParts.size) - for ((name, expression, typeArguments) in nonClassQualifierParts) { + for ((_, _, typeArguments) in nonClassQualifierParts) { if (typeArguments != null) { c.trace.report(TYPE_ARGUMENTS_NOT_ALLOWED.on(typeArguments, "here")) return null diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt index 020d3506d29..107ed26f4d4 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt @@ -189,7 +189,7 @@ class VarianceCheckerCore( (accessor as PropertyAccessorDescriptorImpl).visibility = Visibilities.PRIVATE_TO_THIS } } - else -> throw IllegalStateException("Unexpected descriptor type: ${descriptor.javaClass.name}") + else -> throw IllegalStateException("Unexpected descriptor type: ${descriptor::class.java.name}") } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystemBuilderImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystemBuilderImpl.kt index 2ff9cf11f3b..1120a96aaf0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystemBuilderImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystemBuilderImpl.kt @@ -94,11 +94,11 @@ open class ConstraintSystemBuilderImpl(private val mode: Mode = ConstraintSystem } } - for ((descriptor, typeVariable) in typeParameters.zip(typeVariables)) { + for ((_, typeVariable) in typeParameters.zip(typeVariables)) { allTypeParameterBounds.put(typeVariable, TypeBoundsImpl(typeVariable)) } - for ((typeVariable, typeBounds) in allTypeParameterBounds) { + for ((typeVariable, _) in allTypeParameterBounds) { for (declaredUpperBound in typeVariable.freshTypeParameter.upperBounds) { if (declaredUpperBound.isDefaultBound()) continue //todo remove this line (?) val context = ConstraintContext(TYPE_BOUND_POSITION.position(typeVariable.originalTypeParameter.index)) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt index 541523ebbc7..a5bb97065e2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt @@ -48,7 +48,7 @@ interface TypeBounds { ) { override fun equals(other: Any?): Boolean { if (this === other) return true - if (other == null || javaClass != other.javaClass) return false + if (other == null || this::class.java != other::class.java) return false val bound = other as Bound diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt index 099a6e696a5..907ce3a6a93 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt @@ -123,7 +123,7 @@ object DataFlowValueFactory { receiverValue.getType(), bindingContext, containingDeclarationOrModule) - else -> throw UnsupportedOperationException("Unsupported receiver value: " + receiverValue.javaClass.name) + else -> throw UnsupportedOperationException("Unsupported receiver value: " + receiverValue::class.java.name) } @JvmStatic @@ -242,7 +242,7 @@ object DataFlowValueFactory { } else { IdentifierInfo.qualified(receiverInfo, implicitReceiver.type, - selectorInfo, resolvedCall?.call?.isSafeCall() ?: false) + selectorInfo, resolvedCall.call.isSafeCall()) } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt index ddeb66a6080..1b45e594c81 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt @@ -47,7 +47,7 @@ class DynamicCallableDescriptors(storageManager: StorageManager, builtIns: Kotli fun createDynamicDescriptorScope(call: Call, owner: DeclarationDescriptor) = object : MemberScopeImpl() { override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, ": dynamic candidates for " + call) + p.println(this::class.java.simpleName, ": dynamic candidates for " + call) } override fun getContributedFunctions(name: Name, location: LookupLocation): Collection { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewResolutionOldInference.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewResolutionOldInference.kt index 81f695e92bb..5c6ec1d90f3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewResolutionOldInference.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewResolutionOldInference.kt @@ -56,7 +56,6 @@ import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.isDynamic import org.jetbrains.kotlin.util.OperatorNameConventions -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.sure import java.lang.IllegalStateException import java.util.* @@ -449,7 +448,7 @@ class NewResolutionOldInference( functionContext.tracing.bindReference(variable.resolvedCall.trace, variable.resolvedCall) // todo hacks val functionCall = CallTransformer.CallForImplicitInvoke( - basicCallContext.call.explicitReceiver?.check { useExplicitReceiver }, + basicCallContext.call.explicitReceiver?.takeIf { useExplicitReceiver }, variableReceiver, basicCallContext.call, true) val tracingForInvoke = TracingStrategyForInvoke(calleeExpression, functionCall, variableReceiver.type) val basicCallResolutionContext = basicCallContext.replaceBindingTrace(variable.resolvedCall.trace) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/util/callUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/util/callUtil.kt index c5f829d76cf..4797e2ed062 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/util/callUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/util/callUtil.kt @@ -144,9 +144,9 @@ fun KtElement.getCall(context: BindingContext): Call? { if (element is KtCallElement && element.calleeExpression == null) return null val parent = element.parent - val reference: KtExpression? = when { - parent is KtInstanceExpressionWithLabel -> parent - parent is KtUserType -> parent.parent?.parent as? KtConstructorCalleeExpression + val reference: KtExpression? = when (parent) { + is KtInstanceExpressionWithLabel -> parent + is KtUserType -> parent.parent.parent as? KtConstructorCalleeExpression else -> element.getCalleeExpressionIfAny() } if (reference != null) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/constants/evaluate/ConstantExpressionEvaluator.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/constants/evaluate/ConstantExpressionEvaluator.kt index 7c0edbbe725..e85a357f1b1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/constants/evaluate/ConstantExpressionEvaluator.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/constants/evaluate/ConstantExpressionEvaluator.kt @@ -401,7 +401,7 @@ private class ConstantExpressionEvaluatorVisitor( is IntegerValueTypeConstant -> compileTimeConstant.getType(expectedType) else -> - throw IllegalStateException("Unexpected compileTimeConstant class: ${compileTimeConstant.javaClass.canonicalName}") + throw IllegalStateException("Unexpected compileTimeConstant class: ${compileTimeConstant::class.java.canonicalName}") } if (!constantType.isSubtypeOf(expectedType)) return null diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/Diagnostics.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/Diagnostics.kt index a62070a6f38..da83ac5b40c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/Diagnostics.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/Diagnostics.kt @@ -24,7 +24,7 @@ interface Diagnostics : Iterable { //should not be called on readonly views //any Diagnostics object returned by BindingContext#getDiagnostics() should implement this property val modificationTracker: ModificationTracker - get() = throw IllegalStateException("Trying to obtain modification tracker for Diagnostics object of class $javaClass") + get() = throw IllegalStateException("Trying to obtain modification tracker for Diagnostics object of class ${this::class.java}") fun all(): Collection diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt index 2e0e290a9b2..4619c4da4e7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt @@ -53,7 +53,7 @@ class FunctionImportedFromObject( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): FunctionDescriptor { - throw UnsupportedOperationException("copy() should not be called on ${this.javaClass.simpleName}, was called for $this") + throw UnsupportedOperationException("copy() should not be called on ${this::class.java.simpleName}, was called for $this") } } @@ -73,7 +73,7 @@ class PropertyImportedFromObject( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): FunctionDescriptor { - throw UnsupportedOperationException("copy() should not be called on ${this.javaClass.simpleName}, was called for $this") + throw UnsupportedOperationException("copy() should not be called on ${this::class.java.simpleName}, was called for $this") } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DefaultImportProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DefaultImportProvider.kt index c5f5a111307..9405dafce55 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DefaultImportProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/DefaultImportProvider.kt @@ -30,7 +30,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.getValue -import org.jetbrains.kotlin.utils.addToStdlib.check class DefaultImportProvider( storageManager: StorageManager, @@ -56,7 +55,7 @@ class DefaultImportProvider( defaultImports .filter { it.isAllUnder } .mapNotNull { - it.fqnPart().check { !it.isSubpackageOf(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME) } + it.fqnPart().takeIf { !it.isSubpackageOf(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME) } } val nonKotlinAliasedTypeFqNames = builtinTypeAliases diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt index 6351d01ce66..fb8d72c8e1a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt @@ -40,7 +40,6 @@ import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.getValue import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.utils.Printer -import org.jetbrains.kotlin.utils.addToStdlib.check data class FileScopes(val lexicalScope: LexicalScope, val importingScope: ImportingScope, val importResolver: ImportResolver) @@ -176,7 +175,7 @@ class FileScopeFactory( if (name in excludedNames) return null val classifier = scope.getContributedClassifier(name, location) ?: return null val visible = Visibilities.isVisibleIgnoringReceiver(classifier as DeclarationDescriptorWithVisibility, fromDescriptor) - return classifier.check { filteringKind == if (visible) FilteringKind.VISIBLE_CLASSES else FilteringKind.INVISIBLE_CLASSES } + return classifier.takeIf { filteringKind == if (visible) FilteringKind.VISIBLE_CLASSES else FilteringKind.INVISIBLE_CLASSES } } override fun getContributedVariables(name: Name, location: LookupLocation): Collection { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt index 699577e6395..d445761dc83 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt @@ -254,7 +254,7 @@ class LazyImportScope( override fun toString() = "LazyImportScope: " + debugName override fun printStructure(p: Printer) { - p.println(javaClass.simpleName, ": ", debugName, " {") + p.println(this::class.java.simpleName, ": ", debugName, " {") p.pushIndent() p.popIndent() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt index f5cd3068e39..10650f3da99 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt @@ -33,7 +33,6 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScopeImpl import org.jetbrains.kotlin.storage.MemoizedFunctionToNotNull import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.utils.Printer -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* abstract class AbstractLazyMemberScope @@ -61,7 +60,7 @@ protected constructor( } } getNonDeclaredClasses(name, result) - return result.toReadOnlyList() + return result.toList() } override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? { @@ -92,7 +91,7 @@ protected constructor( getNonDeclaredFunctions(name, result) - return result.toReadOnlyList() + return result.toList() } protected abstract fun getScopeForMemberDeclarationResolution(declaration: KtDeclaration): LexicalScope @@ -125,7 +124,7 @@ protected constructor( getNonDeclaredProperties(name, result) - return result.toReadOnlyList() + return result.toList() } protected abstract fun getNonDeclaredProperties(name: Name, result: MutableSet) @@ -142,7 +141,7 @@ protected constructor( getScopeForMemberDeclarationResolution(ktTypeAlias), ktTypeAlias, trace) - }.toReadOnlyList() + }.toList() protected fun computeDescriptorsFromDeclaredElements( kindFilter: DescriptorKindFilter, @@ -193,7 +192,7 @@ protected constructor( } else throw IllegalArgumentException("Unsupported declaration kind: " + declaration) } - return result.toReadOnlyList() + return result.toList() } abstract fun recordLookup(name: Name, from: LookupLocation) @@ -204,7 +203,7 @@ protected constructor( abstract override fun toString(): String override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.println("thisDescriptor = ", thisDescriptor) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/LocalRedeclarationChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/LocalRedeclarationChecker.kt index 20af1e574d0..75eea064612 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/LocalRedeclarationChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/LocalRedeclarationChecker.kt @@ -57,7 +57,7 @@ abstract class AbstractLocalRedeclarationChecker(val overloadChecker: OverloadCh } } } - else -> throw IllegalStateException("Unexpected type of descriptor: ${newDescriptor.javaClass.name}, descriptor: $newDescriptor") + else -> throw IllegalStateException("Unexpected type of descriptor: ${newDescriptor::class.java.name}, descriptor: $newDescriptor") } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt index 68eacb94e97..58880ad45cd 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt @@ -111,7 +111,7 @@ class TypeAliasQualifier( ?.takeIf { DescriptorUtils.isEnumEntry(it) } override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.println("descriptor = ", descriptor) p.popIndent() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinitionFromAnnotatedTemplate.kt b/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinitionFromAnnotatedTemplate.kt index 857978cce55..1285459fe37 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinitionFromAnnotatedTemplate.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinitionFromAnnotatedTemplate.kt @@ -30,8 +30,8 @@ import org.jetbrains.kotlin.psi.KtScript import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.io.File import kotlin.reflect.KClass -import kotlin.reflect.memberFunctions -import kotlin.reflect.primaryConstructor +import kotlin.reflect.full.memberFunctions +import kotlin.reflect.full.primaryConstructor open class KotlinScriptDefinitionFromAnnotatedTemplate( template: KClass, @@ -95,7 +95,7 @@ open class KotlinScriptDefinitionFromAnnotatedTemplate( } fun makeScriptContents() = BasicScriptContents(file, getAnnotations = { - val classLoader = (template as Any).javaClass.classLoader + val classLoader = (template as Any)::class.java.classLoader try { getAnnotationEntries(file, project) .mapNotNull { psiAnn -> diff --git a/compiler/frontend/src/org/jetbrains/kotlin/script/scriptAnnotationsPreprocessing.kt b/compiler/frontend/src/org/jetbrains/kotlin/script/scriptAnnotationsPreprocessing.kt index bb9613e3246..d55d16e805e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/script/scriptAnnotationsPreprocessing.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/script/scriptAnnotationsPreprocessing.kt @@ -26,7 +26,7 @@ import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.tryCreateCallableMappingFromNamedArgs import kotlin.reflect.KClass import kotlin.reflect.KParameter -import kotlin.reflect.primaryConstructor +import kotlin.reflect.full.primaryConstructor internal val KtAnnotationEntry.typeName: String get() = (typeReference?.typeElement as? KtUserType)?.referencedName.orAnonymous() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTemplateProviderExtensionPoint.kt b/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTemplateProviderExtensionPoint.kt index 30975500741..8d9c6f2e92a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTemplateProviderExtensionPoint.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTemplateProviderExtensionPoint.kt @@ -52,13 +52,13 @@ interface ScriptTemplatesProvider { } fun makeScriptDefsFromTemplatesProviderExtensions(project: Project, - errorsHandler: ((ScriptTemplatesProvider, Exception) -> Unit) = { ep, ex -> throw ex } + errorsHandler: ((ScriptTemplatesProvider, Exception) -> Unit) = { _, ex -> throw ex } ): List = makeScriptDefsFromTemplatesProviders(Extensions.getArea(project).getExtensionPoint(ScriptTemplatesProvider.EP_NAME).extensions.asIterable(), errorsHandler) fun makeScriptDefsFromTemplatesProviders(providers: Iterable, - errorsHandler: ((ScriptTemplatesProvider, Exception) -> Unit) = { ep, ex -> throw ex } + errorsHandler: ((ScriptTemplatesProvider, Exception) -> Unit) = { _, ex -> throw ex } ): List { return providers.filter { it.isValid }.flatMap { provider -> try { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTypeUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTypeUtil.kt index 1f3a56fdb7d..3ce8caa938a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTypeUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/script/scriptTypeUtil.kt @@ -27,6 +27,7 @@ import org.jetbrains.kotlin.serialization.deserialization.findNonGenericClassAcr import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.types.* import kotlin.reflect.* +import kotlin.reflect.full.primaryConstructor data class ScriptParameter(val name: Name, val type: KotlinType) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/storage/ExceptionTracker.kt b/compiler/frontend/src/org/jetbrains/kotlin/storage/ExceptionTracker.kt index 6d767410213..2ba12b00be4 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/storage/ExceptionTracker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/storage/ExceptionTracker.kt @@ -41,6 +41,6 @@ open class ExceptionTracker : ModificationTracker, LockBasedStorageManager.Excep } override fun toString(): String { - return javaClass.name + ": " + modificationCount + return this::class.java.name + ": " + modificationCount } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt index 14bd21445ec..8f6f52ceebe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt @@ -61,7 +61,7 @@ class FakeCallResolver( if (isSuccess) { fakeTrace.commit( - { slice, key -> + { _, key -> // excluding all entries related to fake expression // convert all errors on this expression to ITERATOR_MISSING on callElement key != fake @@ -106,7 +106,7 @@ class FakeCallResolver( valueArguments: List, name: Name, callElement: KtExpression, - onComplete: (KtSimpleNameExpression, Boolean) -> Unit = { x, y -> } + onComplete: (KtSimpleNameExpression, Boolean) -> Unit = { _, _ -> } ): Pair> { val fakeCalleeExpression = KtPsiFactory(project).createSimpleName(name.asString()) val call = CallMaker.makeCallWithExpressions( diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PatternMatchingTypingVisitor.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PatternMatchingTypingVisitor.kt index 207102c1793..0783615369a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PatternMatchingTypingVisitor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PatternMatchingTypingVisitor.kt @@ -373,7 +373,7 @@ class PatternMatchingTypingVisitor internal constructor(facade: ExpressionTyping } override fun visitKtElement(element: KtElement) { - context.trace.report(UNSUPPORTED.on(element, javaClass.canonicalName)) + context.trace.report(UNSUPPORTED.on(element, this::class.java.canonicalName)) } }) return newDataFlowInfo diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt index e0117087d9c..592a4845196 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt @@ -32,7 +32,6 @@ import org.jetbrains.kotlin.psi.KtSuperExpression import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker -import org.jetbrains.kotlin.utils.addToStdlib.singletonList fun resolveUnqualifiedSuperFromExpressionContext( @@ -106,7 +105,7 @@ private fun resolveSupertypesForMethodOfAny(supertypes: Collection, return if (typesWithConcreteOverride.isNotEmpty()) typesWithConcreteOverride else - anyType.singletonList() + listOf(anyType) } private fun resolveSupertypesByCalleeName(supertypes: Collection, calleeName: Name): Collection = diff --git a/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/IncrementalJvmCompilerRunner.kt b/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/IncrementalJvmCompilerRunner.kt index 8a44b3a8fe6..2ba9516d74d 100644 --- a/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/IncrementalJvmCompilerRunner.kt +++ b/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/IncrementalJvmCompilerRunner.kt @@ -274,12 +274,9 @@ class IncrementalJvmCompilerRunner( // there is no point in updating annotation file since all files will be compiled anyway kaptAnnotationsFileUpdater = null } - else -> throw IllegalStateException("Unknown CompilationMode ${compilationMode.javaClass}") + else -> throw IllegalStateException("Unknown CompilationMode ${compilationMode::class.java}") } - @Suppress("NAME_SHADOWING") - var compilationMode = compilationMode - val currentBuildInfo = BuildInfo(startTS = System.currentTimeMillis()) BuildInfo.write(currentBuildInfo, lastBuildInfoFile) val buildDirtyLookupSymbols = HashSet() @@ -356,7 +353,7 @@ class IncrementalJvmCompilerRunner( changesRegistry.registerChanges(currentBuildInfo.startTS, dirtyData) } else { - assert(compilationMode is CompilationMode.Rebuild) { "Unexpected compilation mode: ${compilationMode.javaClass}" } + assert(compilationMode is CompilationMode.Rebuild) { "Unexpected compilation mode: ${compilationMode::class.java}" } changesRegistry.unknownChanges(currentBuildInfo.startTS) } } @@ -400,7 +397,6 @@ class IncrementalJvmCompilerRunner( KotlinClassHeader.Kind.MULTIFILE_CLASS_PART -> { result.addAll(partsByFacadeName(outputClass.classHeader.multifileClassName!!)) } - } } diff --git a/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/snapshots/FileSnapshot.kt b/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/snapshots/FileSnapshot.kt index 3096553badc..442ea83acaa 100644 --- a/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/snapshots/FileSnapshot.kt +++ b/compiler/incremental-compilation-impl/src/org/jetbrains/kotlin/incremental/snapshots/FileSnapshot.kt @@ -30,7 +30,7 @@ class FileSnapshot( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as FileSnapshot diff --git a/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/TestWithWorkingDir.kt b/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/TestWithWorkingDir.kt index c4cb7bafdd8..d80a93864e0 100644 --- a/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/TestWithWorkingDir.kt +++ b/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/TestWithWorkingDir.kt @@ -28,7 +28,7 @@ abstract class TestWithWorkingDir { @Before open fun setUp() { - workingDir = FileUtil.createTempDirectory(this.javaClass.simpleName, null) + workingDir = FileUtil.createTempDirectory(this::class.java.simpleName, null) } @After diff --git a/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/incremental/KotlinStandaloneIncrementalCompilationTest.kt b/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/incremental/KotlinStandaloneIncrementalCompilationTest.kt index 608e553fead..db5fbf8f0aa 100644 --- a/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/incremental/KotlinStandaloneIncrementalCompilationTest.kt +++ b/compiler/incremental-compilation-impl/test/org/jetbrains/kotlin/incremental/KotlinStandaloneIncrementalCompilationTest.kt @@ -81,7 +81,7 @@ class KotlinStandaloneIncrementalCompilationTest : TestWithWorkingDir() { var step = 1 for ((modificationStep, buildLogStep) in modifications.zip(buildLogSteps)) { modificationStep.forEach { it.perform(workingDir, mapWorkingToOriginalFile) } - val (exitCode, compiledSources, compileErrors) = make(cacheDir, sourceRoots, args) + val (_, compiledSources, compileErrors) = make(cacheDir, sourceRoots, args) expectedSB.appendLine(stepLogAsString(step, buildLogStep.compiledKotlinFiles, buildLogStep.compileErrors)) expectedSBWithoutErrors.appendLine(stepLogAsString(step, buildLogStep.compiledKotlinFiles, buildLogStep.compileErrors, includeErrors = false)) diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt index a46cefadb6b..dbf215b56de 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt @@ -120,7 +120,7 @@ class ExpressionCodegen( override fun visitBlockBody(body: IrBlockBody, data: BlockInfo): StackValue { return body.statements.fold(none()) { - r, exp -> + _, exp -> exp.accept(this, data) } } @@ -152,7 +152,7 @@ class ExpressionCodegen( override fun visitContainerExpression(expression: IrContainerExpression, data: BlockInfo): StackValue { val result = expression.statements.fold(none()) { - r, exp -> + _, exp -> //coerceNotToUnit(r.type, Type.VOID_TYPE) exp.accept(this, data) } diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/KnownDescriptors.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/KnownDescriptors.kt index fe606e88931..d43b328fc02 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/KnownDescriptors.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/KnownDescriptors.kt @@ -42,7 +42,7 @@ open class KnownClassDescriptor( override val annotations: Annotations ) : ClassDescriptor { init { - assert(modality != Modality.SEALED) { "Implement getSealedSubclasses() for this class: $javaClass" } + assert(modality != Modality.SEALED) { "Implement getSealedSubclasses() for this class: ${this::class.java}" } } private lateinit var typeConstructor: TypeConstructor diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IrIntrinsicFunction.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IrIntrinsicFunction.kt index 0eea6f7d83b..d2307650014 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IrIntrinsicFunction.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IrIntrinsicFunction.kt @@ -62,7 +62,7 @@ open class IrIntrinsicFunction( open fun invoke(v: InstructionAdapter, codegen: ExpressionCodegen, data: BlockInfo):StackValue { val args = mutableListOf(expression.dispatchReceiver, expression.extensionReceiver) args.addAll(expression.descriptor.valueParameters.mapIndexed { - i, valueParameterDescriptor -> + i, _ -> expression.getValueArgument(i) }) args.filterNotNull().forEachIndexed { i, irExpression -> genArg(irExpression, codegen, i, data) } @@ -108,7 +108,7 @@ fun IrMemberAccessExpression.argTypes(context: JvmBackendContext): ArrayList { return (arrayListOf(this.dispatchReceiver, this.extensionReceiver) + - descriptor.valueParameters.mapIndexed { i, valueParameterDescriptor ->getValueArgument(i)}).filterNotNull() + descriptor.valueParameters.mapIndexed { i, _ ->getValueArgument(i)}).filterNotNull() } fun List.asmTypes(context: JvmBackendContext): List { diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/EnumClassLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/EnumClassLowering.kt index 5fc3150c31f..1f4ed97253c 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/EnumClassLowering.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/EnumClassLowering.kt @@ -42,8 +42,6 @@ import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi2ir.findSingleFunction import org.jetbrains.kotlin.types.* -import org.jetbrains.kotlin.utils.addToStdlib.singletonList -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import org.jetbrains.org.objectweb.asm.Opcodes import java.util.* @@ -169,8 +167,8 @@ class EnumClassLowering(val context: JvmBackendContext) : ClassLoweringPass { private fun lowerEnumEntries() { irClass.declarations.transformFlat { declaration -> if (declaration is IrEnumEntry) { - createFieldForEnumEntry(declaration).singletonList() + - lowerEnumEntryClass(declaration.correspondingClass).singletonOrEmptyList() + listOf(createFieldForEnumEntry(declaration)) + + listOfNotNull(lowerEnumEntryClass(declaration.correspondingClass)) } else null } diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/InnerClassesLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/InnerClassesLowering.kt index ee4451f6004..d0134415da3 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/InnerClassesLowering.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/InnerClassesLowering.kt @@ -32,7 +32,6 @@ import org.jetbrains.kotlin.ir.util.transformFlat import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* class InnerClassesLowering(val context: JvmBackendContext) : ClassLoweringPass { @@ -69,7 +68,7 @@ class InnerClassesLowering(val context: JvmBackendContext) : ClassLoweringPass { private fun lowerConstructors() { irClass.declarations.transformFlat { irMember -> if (irMember is IrConstructor) - lowerConstructor(irMember).singletonList() + listOf(lowerConstructor(irMember)) else null } diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SyntheticAccessorLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SyntheticAccessorLowering.kt index 92f35862f83..4fd837b93f6 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SyntheticAccessorLowering.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SyntheticAccessorLowering.kt @@ -194,7 +194,7 @@ class SyntheticAccessorLowering(val state: GenerationState) : FileLoweringPass, call.extensionReceiver = IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, fromDescriptor.valueParameters[offset++]) } - call.descriptor.valueParameters.forEachIndexed { i, valueParameterDescriptor -> + call.descriptor.valueParameters.forEachIndexed { i, _ -> call.putValueArgument(i, IrGetValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, fromDescriptor.valueParameters[i + offset])) } } diff --git a/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralBlockBuilder.kt b/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralBlockBuilder.kt index 0facf5d0a4c..f66810ef80c 100644 --- a/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralBlockBuilder.kt +++ b/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralBlockBuilder.kt @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.ir2cfg.generators import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir2cfg.builders.BasicBlockBuilder import org.jetbrains.kotlin.ir2cfg.builders.BlockConnectorBuilder -import org.jetbrains.kotlin.utils.toReadOnlyList class GeneralBlockBuilder(override val incoming: BlockConnectorBuilder?) : BasicBlockBuilder { @@ -32,5 +31,5 @@ class GeneralBlockBuilder(override val incoming: BlockConnectorBuilder?) : Basic override val last: IrStatement? get() = elements.lastOrNull() - override fun build() = BasicBlockImpl(elements.toReadOnlyList()) + override fun build() = BasicBlockImpl(elements.toList()) } \ No newline at end of file diff --git a/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralConnectorBuilder.kt b/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralConnectorBuilder.kt index 133abf6cc45..cd71aa202ca 100644 --- a/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralConnectorBuilder.kt +++ b/compiler/ir/ir.ir2cfg/src/org/jetbrains/kotlin/ir2cfg/generators/GeneralConnectorBuilder.kt @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.ir2cfg.generators import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir2cfg.builders.BlockConnectorBuilder import org.jetbrains.kotlin.ir2cfg.graph.BasicBlock -import org.jetbrains.kotlin.utils.toReadOnlyList class GeneralConnectorBuilder(private val element: IrStatement) : BlockConnectorBuilder { @@ -36,8 +35,8 @@ class GeneralConnectorBuilder(private val element: IrStatement) : BlockConnector } override fun build() = when { - next.size <= 1 -> JoinBlockConnector(previous.toReadOnlyList(), element, next.firstOrNull()) - previous.size == 1 -> SplitBlockConnector(previous.single(), element, next.toReadOnlyList()) + next.size <= 1 -> JoinBlockConnector(previous.toList(), element, next.firstOrNull()) + previous.size == 1 -> SplitBlockConnector(previous.single(), element, next.toList()) else -> throw AssertionError("Connector should have either exactly one previous block or no more than one next block, " + "actual previous = ${previous.size}, next = ${next.size}") } diff --git a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ArgumentsGenerationUtils.kt b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ArgumentsGenerationUtils.kt index eeb066305c2..ca5eb33f061 100644 --- a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ArgumentsGenerationUtils.kt +++ b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ArgumentsGenerationUtils.kt @@ -75,7 +75,7 @@ fun StatementGenerator.generateReceiver(startOffset: Int, endOffset: Int, receiv is ExtensionReceiver -> IrGetValueImpl(startOffset, startOffset, receiver.declarationDescriptor.extensionReceiverParameter!!) else -> - TODO("Receiver: ${receiver.javaClass.simpleName}") + TODO("Receiver: ${receiver::class.java.simpleName}") } return if (receiverExpression is IrExpressionWithCopy) @@ -186,7 +186,7 @@ fun StatementGenerator.generateValueArgument(valueArgument: ResolvedValueArgumen is VarargValueArgument -> generateVarargExpression(valueArgument, valueParameter) else -> - TODO("Unexpected valueArgument: ${valueArgument.javaClass.simpleName}") + TODO("Unexpected valueArgument: ${valueArgument::class.java.simpleName}") } fun Generator.getSuperQualifier(resolvedCall: ResolvedCall<*>): ClassDescriptor? { diff --git a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/CallGenerator.kt b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/CallGenerator.kt index 31cd798ee0b..62f2a0c602a 100644 --- a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/CallGenerator.kt +++ b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/CallGenerator.kt @@ -88,7 +88,7 @@ class CallGenerator(statementGenerator: StatementGenerator): StatementGeneratorE is VariableDescriptor -> generateGetVariable(startOffset, endOffset, descriptor, getTypeArguments(resolvedCall), origin) else -> - TODO("Unexpected callable descriptor: $descriptor ${descriptor.javaClass.simpleName}") + TODO("Unexpected callable descriptor: $descriptor ${descriptor::class.java.simpleName}") } private fun generateGetVariable( diff --git a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ErrorExpressionGenerator.kt b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ErrorExpressionGenerator.kt index d8c6eb10fff..a4525a2dc8a 100644 --- a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ErrorExpressionGenerator.kt +++ b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/ErrorExpressionGenerator.kt @@ -31,7 +31,7 @@ class ErrorExpressionGenerator(statementGenerator: StatementGenerator) : Stateme if (ignoreErrors) body() else - throw RuntimeException("${e?.message}: ${ktElement.javaClass.simpleName}:\n${ktElement.text}", e) + throw RuntimeException("${e?.message}: ${ktElement::class.java.simpleName}:\n${ktElement.text}", e) fun generateErrorExpression(ktElement: KtElement, e: Exception): IrExpression = generateErrorExpression(ktElement, e) { diff --git a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt index 969134ab28b..8945048e211 100644 --- a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt +++ b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt @@ -69,7 +69,7 @@ class StatementGenerator( genStmt().assertCast() override fun visitExpression(expression: KtExpression, data: Nothing?): IrStatement = - createDummyExpression(expression, expression.javaClass.simpleName) + createDummyExpression(expression, expression::class.java.simpleName) override fun visitProperty(property: KtProperty, data: Nothing?): IrStatement { val variableDescriptor = getOrFail(BindingContext.VARIABLE, property) diff --git a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/intermediate/CallBuilder.kt b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/intermediate/CallBuilder.kt index cba7e7e3548..0c328dfd82d 100644 --- a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/intermediate/CallBuilder.kt +++ b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/intermediate/CallBuilder.kt @@ -76,7 +76,7 @@ fun CallBuilder.setExplicitReceiverValue(explicitReceiverValue: IntermediateValu val previousCallReceiver = callReceiver callReceiver = object : CallReceiver { override fun call(withDispatchAndExtensionReceivers: (IntermediateValue?, IntermediateValue?) -> IrExpression): IrExpression { - return previousCallReceiver.call { dispatchReceiverValue, extensionReceiverValue -> + return previousCallReceiver.call { dispatchReceiverValue, _ -> val newDispatchReceiverValue = if (hasExtensionReceiver) dispatchReceiverValue else explicitReceiverValue val newExtensionReceiverValue = if (hasExtensionReceiver) explicitReceiverValue else null withDispatchAndExtensionReceivers(newDispatchReceiverValue, newExtensionReceiverValue) diff --git a/compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/util/RenderIrElement.kt b/compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/util/RenderIrElement.kt index fa0e8d42845..98b4eac8241 100644 --- a/compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/util/RenderIrElement.kt +++ b/compiler/ir/ir.tree/src/org/jetbrains/kotlin/ir/util/RenderIrElement.kt @@ -32,10 +32,10 @@ fun IrElement.render() = accept(RenderIrElementVisitor(), null) class RenderIrElementVisitor : IrElementVisitor { override fun visitElement(element: IrElement, data: Nothing?): String = - "? ${element.javaClass.simpleName}" + "? ${element::class.java.simpleName}" override fun visitDeclaration(declaration: IrDeclaration, data: Nothing?): String = - "? ${declaration.javaClass.simpleName} ${declaration.descriptor.ref()}" + "? ${declaration::class.java.simpleName} ${declaration.descriptor.ref()}" override fun visitModuleFragment(declaration: IrModuleFragment, data: Nothing?): String = "MODULE_FRAGMENT ${declaration.descriptor.ref()}" @@ -83,7 +83,7 @@ class RenderIrElementVisitor : IrElementVisitor { "SYNTHETIC_BODY kind=${body.kind}" override fun visitExpression(expression: IrExpression, data: Nothing?): String = - "? ${expression.javaClass.simpleName} type=${expression.type.render()}" + "? ${expression::class.java.simpleName} type=${expression.type.render()}" override fun visitConst(expression: IrConst, data: Nothing?): String = "CONST ${expression.kind} type=${expression.type.render()} value='${expression.value}'" @@ -180,7 +180,7 @@ class RenderIrElementVisitor : IrElementVisitor { "CATCH parameter=${aCatch.parameter.ref()}" override fun visitErrorDeclaration(declaration: IrErrorDeclaration, data: Nothing?): String = - "ERROR_DECL ${declaration.descriptor.javaClass.simpleName} ${declaration.descriptor.ref()}" + "ERROR_DECL ${declaration.descriptor::class.java.simpleName} ${declaration.descriptor.ref()}" override fun visitErrorExpression(expression: IrErrorExpression, data: Nothing?): String = "ERROR_EXPR '${expression.description}' type=${expression.type.render()}" @@ -201,7 +201,7 @@ class RenderIrElementVisitor : IrElementVisitor { val REFERENCE_RENDERER = DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES internal fun IrDeclaration.name(): String = - descriptor.let { it.name.toString() } + descriptor.name.toString() internal fun IrDeclaration.renderDeclared(): String = DECLARATION_RENDERER.render(this.descriptor) diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/builder/LightClassDataProvider.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/builder/LightClassDataProvider.kt index 0dbab553864..95b301572f1 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/builder/LightClassDataProvider.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/builder/LightClassDataProvider.kt @@ -260,7 +260,7 @@ class LightClassDataProviderForClassOrObject(private val classOrObject: KtClassO } override fun toString(): String { - return this.javaClass.name + " for " + classOrObject.name + return this::class.java.name + " for " + classOrObject.name } } @@ -320,7 +320,7 @@ sealed class LightClassDataProviderForFileFacade private constructor( } override fun toString(): String { - return this.javaClass.name + " for $facadeFqName" + return this::class.java.name + " for $facadeFqName" } // create delegate by relevant files in project source using LightClassGenerationSupport diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForAnonymousDeclaration.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForAnonymousDeclaration.kt index a3c495835e2..6dea7347a66 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForAnonymousDeclaration.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForAnonymousDeclaration.kt @@ -87,7 +87,7 @@ internal open class KtLightClassForAnonymousDeclaration(classOrObject: KtClassOr override fun equals(other: Any?): Boolean { if (this === other) return true - if (other == null || javaClass != other.javaClass) return false + if (other == null || this::class.java != other::class.java) return false val aClass = other as KtLightClassForAnonymousDeclaration diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForFacade.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForFacade.kt index 81a1595261e..8f3d82e571c 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForFacade.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForFacade.kt @@ -247,7 +247,7 @@ class KtLightClassForFacade private constructor( } override fun equals(other: Any?): Boolean { - if (other == null || javaClass != other.javaClass) { + if (other == null || this::class.java != other::class.java) { return false } diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForLocalDeclaration.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForLocalDeclaration.kt index 236c9ee52a0..dc260dbcc49 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForLocalDeclaration.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForLocalDeclaration.kt @@ -60,7 +60,7 @@ open class KtLightClassForLocalDeclaration( if (createWrapper) { return object : LightMethod(myManager, method, containingClass!!, KotlinLanguage.INSTANCE) { override fun getParent(): PsiElement { - return getContainingClass()!! + return getContainingClass() } override fun getName(): String { diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForSourceDeclaration.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForSourceDeclaration.kt index 9cfab066326..1142d032e58 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForSourceDeclaration.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/classes/KtLightClassForSourceDeclaration.kt @@ -161,7 +161,7 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC override fun equals(other: Any?): Boolean { if (this === other) return true - if (other == null || javaClass != other.javaClass) return false + if (other == null || this::class.java != other::class.java) return false val aClass = other as KtLightClassForSourceDeclaration @@ -313,7 +313,7 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC return this } - override fun toString() = "${this.javaClass.simpleName}:${classOrObject.getDebugText()}" + override fun toString() = "${this::class.java.simpleName}:${classOrObject.getDebugText()}" override fun getOwnInnerClasses(): List { val result = ArrayList() diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/duplicateJvmSignatureUtil.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/duplicateJvmSignatureUtil.kt index 58979f746ce..14dd494d918 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/duplicateJvmSignatureUtil.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/duplicateJvmSignatureUtil.kt @@ -91,7 +91,7 @@ class FilteredJvmDiagnostics(val jvmDiagnostics: Diagnostics, val otherDiagnosti val higherPriority = setOf>( CONFLICTING_OVERLOADS, REDECLARATION, NOTHING_TO_OVERRIDE, MANY_IMPL_MEMBER_NOT_IMPLEMENTED) return otherDiagnostics.forElement(psiElement).any { it.factory in higherPriority } - || psiElement is KtPropertyAccessor && alreadyReported(psiElement.parent!!) + || psiElement is KtPropertyAccessor && alreadyReported(psiElement.parent) } override fun forElement(psiElement: PsiElement): Collection { diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightAnnotation.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightAnnotation.kt index f3262bcec8a..ad4e6c24e58 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightAnnotation.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightAnnotation.kt @@ -171,7 +171,7 @@ class KtLightAnnotation( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return kotlinOrigin == (other as KtLightAnnotation).kotlinOrigin } diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightFieldImpl.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightFieldImpl.kt index 728b8dd98d5..7e52244b3fa 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightFieldImpl.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightFieldImpl.kt @@ -96,7 +96,7 @@ sealed class KtLightFieldImpl( override fun isValid() = containingClass.isValid - override fun toString(): String = "${this.javaClass.simpleName}:$name" + override fun toString(): String = "${this::class.java.simpleName}:$name" override fun equals(other: Any?): Boolean = other is KtLightField && diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightMethod.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightMethod.kt index d350de370c0..304fd2cf653 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightMethod.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/elements/KtLightMethod.kt @@ -199,7 +199,7 @@ sealed class KtLightMethodImpl( override fun hashCode(): Int = ((name.hashCode() * 31 + (lightMethodOrigin?.hashCode() ?: 0)) * 31 + containingClass.hashCode()) * 31 + clsDelegate.hashCode() - override fun toString(): String = "${this.javaClass.simpleName}:$name" + override fun toString(): String = "${this::class.java.simpleName}:$name" private class KtLightMethodForDeclaration( delegate: PsiMethod, origin: LightMemberOrigin?, containingClass: KtLightClass diff --git a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/lightClassUtils.kt b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/lightClassUtils.kt index 445deddff8b..73521d08d79 100644 --- a/compiler/light-classes/src/org/jetbrains/kotlin/asJava/lightClassUtils.kt +++ b/compiler/light-classes/src/org/jetbrains/kotlin/asJava/lightClassUtils.kt @@ -33,8 +33,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration -import org.jetbrains.kotlin.utils.addToStdlib.singletonList -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* fun KtClassOrObject.toLightClass(): KtLightClass? = LightClassGenerationSupport.getInstance(project).getLightClass(this) @@ -47,11 +45,11 @@ fun KtFile.findFacadeClass(): KtLightClass? { fun KtElement.toLightElements(): List = when (this) { - is KtClassOrObject -> toLightClass().singletonOrEmptyList() + is KtClassOrObject -> listOfNotNull(toLightClass()) is KtNamedFunction, is KtSecondaryConstructor -> LightClassUtil.getLightClassMethods(this as KtFunction) is KtProperty -> LightClassUtil.getLightClassPropertyMethods(this).allDeclarations - is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethod(this).singletonOrEmptyList() + is KtPropertyAccessor -> listOfNotNull(LightClassUtil.getLightClassAccessorMethod(this)) is KtParameter -> ArrayList().let { elements -> toPsiParameters().toCollection(elements) LightClassUtil.getLightClassPropertyMethods(this).toCollection(elements) @@ -60,7 +58,7 @@ fun KtElement.toLightElements(): List = elements } is KtTypeParameter -> toPsiTypeParameters() - is KtFile -> findFacadeClass().singletonOrEmptyList() + is KtFile -> listOfNotNull(findFacadeClass()) else -> listOf() } @@ -70,8 +68,8 @@ fun PsiElement.toLightMethods(): List = is KtProperty -> LightClassUtil.getLightClassPropertyMethods(this).toList() is KtParameter -> LightClassUtil.getLightClassPropertyMethods(this).toList() is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethods(this) - is KtClass -> toLightClass()?.constructors?.firstOrNull().singletonOrEmptyList() - is PsiMethod -> this.singletonList() + is KtClass -> listOfNotNull(toLightClass()?.constructors?.firstOrNull()) + is PsiMethod -> listOf(this) else -> listOf() } diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignature.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignature.kt index d858cd5f650..0e3957b42a0 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignature.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignature.kt @@ -24,7 +24,6 @@ import org.jetbrains.kotlin.descriptors.synthetic.SyntheticMemberDescriptor import org.jetbrains.kotlin.resolve.descriptorUtil.hasDefaultValue import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.checker.KotlinTypeChecker -import org.jetbrains.kotlin.utils.singletonOrEmptyList interface SpecificityComparisonCallbacks { fun isNonSubtypeNotLessSpecific(specific: KotlinType, general: KotlinType): Boolean @@ -62,7 +61,7 @@ class FlatSignature private constructor( return FlatSignature(origin, descriptor.typeParameters, valueParameterTypes = - extensionReceiverType.singletonOrEmptyList() + parameterTypes, + listOfNotNull(extensionReceiverType) + parameterTypes, hasExtensionReceiver = extensionReceiverType != null, hasVarargs = descriptor.valueParameters.any { it.varargElementType != null }, numDefaults = numDefaults, diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt index 4b533e46df0..3081a6b6762 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt @@ -24,14 +24,13 @@ import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind import org.jetbrains.kotlin.resolve.scopes.receivers.DetailedReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.QualifierReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo -import org.jetbrains.kotlin.utils.addToStdlib.check class KnownResultProcessor( val result: Collection ): ScopeTowerProcessor { override fun process(data: TowerData) - = if (data == TowerData.Empty) listOfNotNull(result.check { it.isNotEmpty() }) else emptyList() + = if (data == TowerData.Empty) listOfNotNull(result.takeIf { it.isNotEmpty() }) else emptyList() } class CompositeScopeTowerProcessor( @@ -46,7 +45,7 @@ internal abstract class AbstractSimpleScopeTowerProcessor - override fun process(data: TowerData): List> = listOfNotNull(simpleProcess(data).check { it.isNotEmpty() }) + override fun process(data: TowerData): List> = listOfNotNull(simpleProcess(data).takeIf { it.isNotEmpty() }) } private typealias CandidatesCollector = @@ -173,7 +172,7 @@ private fun > createSimpleProcessor( } else { assert(explicitReceiver == null) { - "Illegal explicit receiver: $explicitReceiver(${explicitReceiver!!.javaClass.simpleName})" + "Illegal explicit receiver: $explicitReceiver(${explicitReceiver!!::class.java.simpleName})" } return NoExplicitReceiverScopeTowerProcessor(context, collectCandidates) } diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerLevels.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerLevels.kt index 05e5bd08fa0..d26b112ad45 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerLevels.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerLevels.kt @@ -42,8 +42,6 @@ import org.jetbrains.kotlin.types.isDynamic import org.jetbrains.kotlin.types.typeUtil.getImmediateSuperclassNotAny import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.singletonOrEmptyList -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* internal abstract class AbstractScopeTowerLevel( @@ -148,7 +146,7 @@ internal class MemberScopeTowerLevel( override fun getFunctions(name: Name, extensionReceiver: ReceiverValueWithSmartCastInfo?): Collection> { return collectMembers { getContributedFunctions(name, location) + it.getInnerConstructors(name, location) + - syntheticScopes.collectSyntheticMemberFunctions(it.singletonOrEmptyList(), name, location) + syntheticScopes.collectSyntheticMemberFunctions(listOfNotNull(it), name, location) } } } @@ -278,7 +276,7 @@ private fun ResolutionScope.getContributedFunctionsAndConstructors( syntheticConstructorsProvider.getSyntheticConstructors(classifier, location).filterTo(result) { it.dispatchReceiverParameter == null } } - return result.toReadOnlyList() + return result.toList() } private fun ClassifierDescriptor.getCallableConstructors(): Collection = diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerResolver.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerResolver.kt index ef4923119c7..7cc37cfe3f9 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerResolver.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/TowerResolver.kt @@ -25,7 +25,6 @@ import org.jetbrains.kotlin.resolve.scopes.ImportingScope import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo import org.jetbrains.kotlin.resolve.scopes.utils.parentsWithSelf -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* interface Candidate { @@ -235,11 +234,11 @@ class TowerResolver { override fun getSuccessfulCandidates(): Collection? = getResolved() - fun getResolved() = currentCandidates.check { currentLevel == ResolutionCandidateApplicability.RESOLVED } + fun getResolved() = currentCandidates.takeIf { currentLevel == ResolutionCandidateApplicability.RESOLVED } - fun getResolvedLowPriority() = currentCandidates.check { currentLevel == ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY } + fun getResolvedLowPriority() = currentCandidates.takeIf { currentLevel == ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY } - fun getErrors() = currentCandidates.check { + fun getErrors() = currentCandidates.takeIf { currentLevel == null || currentLevel!! > ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY } diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalChainedScope.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalChainedScope.kt index eedc723c805..27a668a8843 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalChainedScope.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalChainedScope.kt @@ -49,7 +49,7 @@ class LexicalChainedScope @JvmOverloads constructor( override fun toString(): String = kind.toString() override fun printStructure(p: Printer) { - p.println(javaClass.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, + p.println(this::class.java.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, " with implicitReceiver: ", implicitReceiver?.value ?: "NONE", " {") p.pushIndent() diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalScopeImpl.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalScopeImpl.kt index 32441e82118..aa9f1bae089 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalScopeImpl.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalScopeImpl.kt @@ -36,7 +36,7 @@ class LexicalScopeImpl @JvmOverloads constructor( override fun toString(): String = kind.toString() override fun printStructure(p: Printer) { - p.println(javaClass.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, + p.println(this::class.java.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, " with implicitReceiver: ", implicitReceiver?.value ?: "NONE", " {") p.pushIndent() diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalWritableScope.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalWritableScope.kt index f8e420bf573..08872a763e7 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalWritableScope.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/LexicalWritableScope.kt @@ -88,7 +88,7 @@ class LexicalWritableScope( override fun toString(): String = kind.toString() override fun printStructure(p: Printer) { - p.println(javaClass.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, + p.println(this::class.java.simpleName, ": ", kind, "; for descriptor: ", ownerDescriptor.name, " with implicitReceiver: ", implicitReceiver?.value ?: "NONE", " {") p.pushIndent() diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/utils/ScopeUtils.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/utils/ScopeUtils.kt index 157c3357983..73075566e22 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/utils/ScopeUtils.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/scopes/utils/ScopeUtils.kt @@ -116,10 +116,10 @@ private class MemberScopeToImportingScopeAdapter(override val parent: ImportingS override fun hashCode() = memberScope.hashCode() - override fun toString() = "${javaClass.simpleName} for $memberScope" + override fun toString() = "${this::class.java.simpleName} for $memberScope" override fun printStructure(p: Printer) { - p.println(javaClass.simpleName) + p.println(this::class.java.simpleName) p.pushIndent() memberScope.printScopeStructure(p.withholdIndentOnce()) diff --git a/compiler/tests-common/org/jetbrains/kotlin/checkers/LazyOperationsLog.kt b/compiler/tests-common/org/jetbrains/kotlin/checkers/LazyOperationsLog.kt index 6a37671fa73..50124b090e1 100644 --- a/compiler/tests-common/org/jetbrains/kotlin/checkers/LazyOperationsLog.kt +++ b/compiler/tests-common/org/jetbrains/kotlin/checkers/LazyOperationsLog.kt @@ -130,7 +130,7 @@ class LazyOperationsLog( val id = objectId(o) - val aClass = o.javaClass + val aClass = o::class.java sb.append(if (aClass.isAnonymousClass) aClass.name.substringAfterLast('.') else aClass.simpleName).append("@$id") fun Any.appendQuoted() { @@ -139,15 +139,15 @@ class LazyOperationsLog( when { o is Named -> o.name.appendQuoted() - o.javaClass.simpleName == "LazyJavaClassifierType" -> { + o::class.java.simpleName == "LazyJavaClassifierType" -> { val javaType = o.field>("javaType") javaType.psi.presentableText.appendQuoted() } - o.javaClass.simpleName == "LazyJavaClassTypeConstructor" -> { + o::class.java.simpleName == "LazyJavaClassTypeConstructor" -> { val javaClass = o.field("this\$0").field("jClass") javaClass.psi.name!!.appendQuoted() } - o.javaClass.simpleName == "DeserializedType" -> { + o::class.java.simpleName == "DeserializedType" -> { val typeDeserializer = o.field("typeDeserializer") val context = typeDeserializer.field("c") val typeProto = o.field("typeProto") @@ -191,7 +191,7 @@ class LazyOperationsLog( } private fun Any.field(name: String): T { - val field = this.javaClass.getDeclaredField(name) + val field = this::class.java.getDeclaredField(name) field.isAccessible = true @Suppress("UNCHECKED_CAST") return field.get(this) as T diff --git a/compiler/tests-common/org/jetbrains/kotlin/checkers/LoggingStorageManager.kt b/compiler/tests-common/org/jetbrains/kotlin/checkers/LoggingStorageManager.kt index e222c87b0e4..463fa2d6c07 100644 --- a/compiler/tests-common/org/jetbrains/kotlin/checkers/LoggingStorageManager.kt +++ b/compiler/tests-common/org/jetbrains/kotlin/checkers/LoggingStorageManager.kt @@ -54,7 +54,7 @@ class LoggingStorageManager( } private fun computeCallerData(lambda: Any, wrapper: Any, arguments: List, result: Any?): CallData { - val lambdaClass = lambda.javaClass + val lambdaClass = lambda::class.java val outerClass: Class? = lambdaClass.enclosingClass @@ -79,7 +79,7 @@ class LoggingStorageManager( val value = field.get(outerInstance) if (value == null) return@firstOrNull false - val valueClass = value.javaClass + val valueClass = value::class.java val functionField = valueClass.findFunctionField() if (functionField == null) return@firstOrNull false @@ -93,7 +93,7 @@ class LoggingStorageManager( if (wrappedLambdaField != null) { wrappedLambdaField.isAccessible = true val wrappedLambda = wrappedLambdaField.get(lambda) - return CallData(outerInstance, null, enclosingEntity(wrappedLambda.javaClass), arguments, result) + return CallData(outerInstance, null, enclosingEntity(wrappedLambda::class.java), arguments, result) } } @@ -102,7 +102,7 @@ class LoggingStorageManager( return CallData(outerInstance, containingField, enclosingEntity, arguments, result) } - private fun enclosingEntity(_class: Class): GenericDeclaration? { + private fun enclosingEntity(_class: Class): GenericDeclaration? { val result = _class.enclosingConstructor ?: _class.enclosingMethod ?: _class.enclosingClass @@ -117,8 +117,7 @@ class LoggingStorageManager( while (true) { result.addAll(c.declaredFields.toList()) @Suppress("UNCHECKED_CAST") - val superClass = (c as Class).superclass as Class? - if (superClass == null) break + val superClass = (c as Class).superclass ?: break if (c == superClass) break c = superClass } diff --git a/compiler/tests-common/org/jetbrains/kotlin/resolve/constants/evaluate/AbstractCompileTimeConstantEvaluatorTest.kt b/compiler/tests-common/org/jetbrains/kotlin/resolve/constants/evaluate/AbstractCompileTimeConstantEvaluatorTest.kt index 321c96a671d..eb165845013 100644 --- a/compiler/tests-common/org/jetbrains/kotlin/resolve/constants/evaluate/AbstractCompileTimeConstantEvaluatorTest.kt +++ b/compiler/tests-common/org/jetbrains/kotlin/resolve/constants/evaluate/AbstractCompileTimeConstantEvaluatorTest.kt @@ -37,7 +37,7 @@ abstract class AbstractCompileTimeConstantEvaluatorTest : AbstractAnnotationDesc // Test directives should look like [// val testedPropertyName: expectedValue] fun doConstantTest(path: String) { doTest(path) { - property, context -> + property, _ -> val compileTimeConstant = property.compileTimeInitializer if (compileTimeConstant is StringValue) { "\\\"${compileTimeConstant.value}\\\"" diff --git a/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt b/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt index 3ec10b5fe7b..2d47ba92894 100644 --- a/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/cli/WrongBytecodeVersionTest.kt @@ -35,7 +35,7 @@ class WrongBytecodeVersionTest : KtUsefulTestCase() { val librarySource = File(directory, "A.kt") val usageSource = File(directory, "B.kt") - val tmpdir = KotlinTestUtils.tmpDir(javaClass.simpleName) + val tmpdir = KotlinTestUtils.tmpDir(this::class.java.simpleName) val environment = KotlinTestUtils.createEnvironmentWithMockJdkAndIdeaAnnotations(testRootDisposable) LoadDescriptorUtil.compileKotlinToDirAndGetModule(listOf(librarySource), tmpdir, environment) diff --git a/compiler/tests/org/jetbrains/kotlin/cli/jvm/repl/GenericReplTest.kt b/compiler/tests/org/jetbrains/kotlin/cli/jvm/repl/GenericReplTest.kt index d73a2bec5c4..12954a06130 100644 --- a/compiler/tests/org/jetbrains/kotlin/cli/jvm/repl/GenericReplTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/cli/jvm/repl/GenericReplTest.kt @@ -148,7 +148,7 @@ internal class TestRepl( } private fun makeScriptDefinition(templateClasspath: List, templateClassName: String): KotlinScriptDefinition { - val classloader = URLClassLoader(templateClasspath.map { it.toURI().toURL() }.toTypedArray(), this.javaClass.classLoader) + val classloader = URLClassLoader(templateClasspath.map { it.toURI().toURL() }.toTypedArray(), this::class.java.classLoader) val cls = classloader.loadClass(templateClassName) return KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, emptyMap()) } diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractWriteSignatureTest.kt b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractWriteSignatureTest.kt index be702e9e938..64bd5bd8d9b 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractWriteSignatureTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractWriteSignatureTest.kt @@ -144,7 +144,7 @@ abstract class AbstractWriteSignatureTest : TestCaseWithTmpdir() { val classDir = classFile.parentFile val classLastName = classFile.name val packageFacadePrefix = classLastName.replace(".class", "\$") - classDir.listFiles { dir, lastName -> + classDir.listFiles { _, lastName -> lastName.startsWith(packageFacadePrefix) && lastName.endsWith(".class") }.forEach { packageFacadeFile -> processClassFile(checker, packageFacadeFile) diff --git a/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTemplateTest.kt b/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTemplateTest.kt index 68249bb22ca..b8d94195231 100644 --- a/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTemplateTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTemplateTest.kt @@ -278,7 +278,7 @@ class ScriptTemplateTest { try { return if (runIsolated) KotlinToJVMBytecodeCompiler.compileScript(environment, paths) - else KotlinToJVMBytecodeCompiler.compileScript(environment, this.javaClass.classLoader) + else KotlinToJVMBytecodeCompiler.compileScript(environment, this::class.java.classLoader) } catch (e: CompilationException) { messageCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(e), @@ -333,15 +333,17 @@ class TestKotlinScriptDependenciesResolver : TestKotlinScriptDummyDependenciesRe val cp = script.annotations.flatMap { when (it) { is DependsOn -> if (it.path == "@{runtime}") listOf(kotlinPaths.runtimePath, kotlinPaths.scriptRuntimePath) else listOf(File(it.path)) - is DependsOnTwo -> listOf(it.path1, it.path2).flatMap { it?.let { - when { - it.isBlank() -> emptyList() - it == "@{runtime}" -> listOf(kotlinPaths.runtimePath, kotlinPaths.scriptRuntimePath) - else -> listOf(File(it)) + is DependsOnTwo -> listOf(it.path1, it.path2).flatMap { + it.let { + when { + it.isBlank() -> emptyList() + it == "@{runtime}" -> listOf(kotlinPaths.runtimePath, kotlinPaths.scriptRuntimePath) + else -> listOf(File(it)) + } } - }} + } is InvalidScriptResolverAnnotation -> throw Exception("Invalid annotation ${it.name}", it.error) - else -> throw Exception("Unknown annotation ${it.javaClass}") + else -> throw Exception("Unknown annotation ${it::class.java}") } } return object : KotlinScriptExternalDependencies { diff --git a/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTest.kt b/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTest.kt index d2f92e2dd04..0b0c81b2504 100644 --- a/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/scripts/ScriptTest.kt @@ -117,7 +117,7 @@ class ScriptTest : KtUsefulTestCase() { try { return if (runIsolated) KotlinToJVMBytecodeCompiler.compileScript(environment, paths) - else KotlinToJVMBytecodeCompiler.compileScript(environment, this.javaClass.classLoader) + else KotlinToJVMBytecodeCompiler.compileScript(environment, this::class.java.classLoader) } catch (e: CompilationException) { messageCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(e), diff --git a/compiler/tests/org/jetbrains/kotlin/serialization/builtins/BuiltInsSerializerTest.kt b/compiler/tests/org/jetbrains/kotlin/serialization/builtins/BuiltInsSerializerTest.kt index 82a898d777b..39cae7efdfc 100644 --- a/compiler/tests/org/jetbrains/kotlin/serialization/builtins/BuiltInsSerializerTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/serialization/builtins/BuiltInsSerializerTest.kt @@ -35,7 +35,7 @@ class BuiltInsSerializerTest : TestCaseWithTmpdir() { tmpdir, srcDirs = listOf(File(source)), extraClassPath = listOf(ForTestCompileRuntime.runtimeJarForTests()), - onComplete = { totalSize, totalFiles -> } + onComplete = { _, _ -> } ) val module = KotlinTestUtils.createEmptyModule("", DefaultBuiltIns.Instance) diff --git a/compiler/util/src/org/jetbrains/kotlin/utils/reflectionUtil.kt b/compiler/util/src/org/jetbrains/kotlin/utils/reflectionUtil.kt index 3de29fa8c0c..215f1c9daba 100644 --- a/compiler/util/src/org/jetbrains/kotlin/utils/reflectionUtil.kt +++ b/compiler/util/src/org/jetbrains/kotlin/utils/reflectionUtil.kt @@ -16,7 +16,6 @@ package org.jetbrains.kotlin.utils -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import kotlin.reflect.* import kotlin.reflect.full.isSubclassOf @@ -106,8 +105,8 @@ private fun tryCreateCallableMapping(callable: KCallable<*>, args: Iterator< } ArgsTraversalState.NAMED -> { assert(arg.name != null) - val parIdx = unboundParams.indexOfFirst { it.name == arg.name }.check { it >= 0 } - ?: return null // failed to match: no matching named parameter found + val parIdx = unboundParams.indexOfFirst { it.name == arg.name }.takeIf { it >= 0 } + ?: return null // failed to match: no matching named parameter found val par = unboundParams.removeAt(parIdx) val cvtRes = converter.tryConvertSingle(par, arg) if (cvtRes is ArgsConverter.Result.Success) { @@ -184,7 +183,7 @@ private class StringArgsConverter : ArgsConverter { DoubleArray::class -> args.map { it?.toDoubleOrNull() } BooleanArray::class -> args.map { it?.toBoolean() } else -> null - }?.toList()?.check { list -> list.none { it == null } }?.toTypedArray() + }?.toList()?.takeIf { list -> list.none { it == null } }?.toTypedArray() val parameterType = parameter.type if (parameterType.jvmErasure.java.isArray) { diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/ErasedOverridabilityCondition.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/ErasedOverridabilityCondition.kt index 10cef6f8953..846030b91e6 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/ErasedOverridabilityCondition.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/ErasedOverridabilityCondition.kt @@ -25,7 +25,6 @@ import org.jetbrains.kotlin.load.java.lazy.types.RawTypeImpl import org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition import org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition.Result import org.jetbrains.kotlin.resolve.OverridingUtil -import org.jetbrains.kotlin.utils.singletonOrEmptyList class ErasedOverridabilityCondition : ExternalOverridabilityCondition { override fun isOverridable(superDescriptor: CallableDescriptor, subDescriptor: CallableDescriptor, subClassDescriptor: ClassDescriptor?): Result { @@ -36,7 +35,7 @@ class ErasedOverridabilityCondition : ExternalOverridabilityCondition { val signatureTypes = subDescriptor.valueParameters.asSequence().map { it.type } + subDescriptor.returnType!! + - subDescriptor.extensionReceiverParameter?.type.singletonOrEmptyList() + listOfNotNull(subDescriptor.extensionReceiverParameter?.type) if (signatureTypes.any { it.arguments.isNotEmpty() && it.unwrap() !is RawTypeImpl }) return Result.UNKNOWN diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/LazyJavaPackageFragmentProvider.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/LazyJavaPackageFragmentProvider.kt index 68d99a875f3..dc44bdb7395 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/LazyJavaPackageFragmentProvider.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/LazyJavaPackageFragmentProvider.kt @@ -21,7 +21,6 @@ import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaPackageFragment import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.storage.MemoizedFunctionToNullable -import org.jetbrains.kotlin.utils.emptyOrSingletonList class LazyJavaPackageFragmentProvider( components: JavaResolverComponents @@ -41,7 +40,7 @@ class LazyJavaPackageFragmentProvider( private fun getPackageFragment(fqName: FqName) = packageFragments(fqName) - override fun getPackageFragments(fqName: FqName) = emptyOrSingletonList(getPackageFragment(fqName)) + override fun getPackageFragments(fqName: FqName) = listOfNotNull(getPackageFragment(fqName)) override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean) = getPackageFragment(fqName)?.getSubPackageFqNames().orEmpty() diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/JvmPackageScope.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/JvmPackageScope.kt index e44a8603b62..957ccb8a000 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/JvmPackageScope.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/JvmPackageScope.kt @@ -31,7 +31,6 @@ import org.jetbrains.kotlin.storage.getValue import org.jetbrains.kotlin.util.collectionUtils.getFirstClassifierDiscriminateHeaders import org.jetbrains.kotlin.util.collectionUtils.getFromAllScopes import org.jetbrains.kotlin.utils.Printer -import org.jetbrains.kotlin.utils.toReadOnlyList class JvmPackageScope( private val c: LazyJavaResolverContext, @@ -43,7 +42,7 @@ class JvmPackageScope( private val kotlinScopes by c.storageManager.createLazyValue { packageFragment.binaryClasses.values.mapNotNull { partClass -> c.components.deserializedDescriptorResolver.createKotlinPackagePartScope(packageFragment, partClass) - }.toReadOnlyList() + }.toList() } override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? { @@ -78,7 +77,7 @@ class JvmPackageScope( } override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.println("containingDeclaration: $packageFragment") diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassDescriptor.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassDescriptor.kt index fc8dc1e6f02..a63f2dead58 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassDescriptor.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassDescriptor.kt @@ -48,8 +48,6 @@ import org.jetbrains.kotlin.serialization.deserialization.NotFoundClasses import org.jetbrains.kotlin.storage.getValue import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.check -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* class LazyJavaClassDescriptor( @@ -184,11 +182,11 @@ class LazyJavaClassDescriptor( }) } - return if (result.isNotEmpty()) result.toReadOnlyList() else listOf(c.module.builtIns.anyType) + return if (result.isNotEmpty()) result.toList() else listOf(c.module.builtIns.anyType) } private fun getPurelyImplementedSupertype(): KotlinType? { - val annotatedPurelyImplementedFqName = getPurelyImplementsFqNameFromAnnotation()?.check { + val annotatedPurelyImplementedFqName = getPurelyImplementsFqNameFromAnnotation()?.takeIf { !it.isRoot && it.toUnsafe().startsWith(KotlinBuiltIns.BUILT_INS_PACKAGE_NAME) } diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt index 6f1ba83c234..6a320382bc0 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt @@ -57,7 +57,6 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.utils.* -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import java.util.* @@ -87,8 +86,8 @@ class LazyJavaClassMemberScope( } enhanceSignatures( - result.ifEmpty { emptyOrSingletonList(createDefaultConstructor()) } - ).toReadOnlyList() + result.ifEmpty { listOfNotNull(createDefaultConstructor()) } + ).toList() } override fun JavaMethodDescriptor.isVisibleAsFunction(): Boolean { @@ -192,8 +191,7 @@ class LazyJavaClassMemberScope( val overriddenBuiltinProperty = getter?.getOverriddenBuiltinWithDifferentJvmName() val specialGetterName = overriddenBuiltinProperty?.getBuiltinSpecialPropertyGetterName() if (specialGetterName != null - && !this@LazyJavaClassMemberScope.ownerDescriptor.hasRealKotlinSuperClassWithOverrideOf( - overriddenBuiltinProperty!!) + && !this@LazyJavaClassMemberScope.ownerDescriptor.hasRealKotlinSuperClassWithOverrideOf(overriddenBuiltinProperty) ) { return findGetterByName(specialGetterName, functions) } @@ -209,7 +207,7 @@ class LazyJavaClassMemberScope( descriptor -> if (descriptor.valueParameters.size != 0) return@factory null - descriptor.check { KotlinTypeChecker.DEFAULT.isSubtypeOf(descriptor.returnType ?: return@check false, type) } + descriptor.takeIf { KotlinTypeChecker.DEFAULT.isSubtypeOf(descriptor.returnType ?: return@takeIf false, type) } } } @@ -221,7 +219,7 @@ class LazyJavaClassMemberScope( if (descriptor.valueParameters.size != 1) return@factory null if (!KotlinBuiltIns.isUnit(descriptor.returnType ?: return@factory null)) return@factory null - descriptor.check { KotlinTypeChecker.DEFAULT.equalTypes(descriptor.valueParameters.single().type, type) } + descriptor.takeIf { KotlinTypeChecker.DEFAULT.equalTypes(descriptor.valueParameters.single().type, type) } } } diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaScope.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaScope.kt index e11fd6efa90..6eb5ce7673b 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaScope.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaScope.kt @@ -46,7 +46,6 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberScopeImpl() { @@ -89,7 +88,7 @@ abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberS computeNonDeclaredFunctions(result, name) - enhanceSignatures(result).toReadOnlyList() + enhanceSignatures(result).toList() } open protected fun JavaMethodDescriptor.isVisibleAsFunction() = true @@ -245,9 +244,9 @@ abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberS computeNonDeclaredProperties(name, properties) if (DescriptorUtils.isAnnotationClass(ownerDescriptor)) - properties.toReadOnlyList() + properties.toList() else - enhanceSignatures(properties).toReadOnlyList() + enhanceSignatures(properties).toList() } private fun resolveProperty(field: JavaField): PropertyDescriptor { @@ -337,7 +336,7 @@ abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberS } } - return result.toReadOnlyList() + return result.toList() } protected abstract fun computeClassNames(kindFilter: DescriptorKindFilter, nameFilter: ((Name) -> Boolean)?): Set @@ -345,7 +344,7 @@ abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberS override fun toString() = "Lazy scope for $ownerDescriptor" override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.println("containingDeclaration: $ownerDescriptor") diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/types/JavaTypeResolver.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/types/JavaTypeResolver.kt index f0044598a6a..b5d423d23de 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/types/JavaTypeResolver.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/types/JavaTypeResolver.kt @@ -37,7 +37,6 @@ import org.jetbrains.kotlin.types.Variance.* import org.jetbrains.kotlin.types.typeUtil.createProjection import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections import org.jetbrains.kotlin.utils.sure -import org.jetbrains.kotlin.utils.toReadOnlyList private val JAVA_LANG_CLASS_FQ_NAME: FqName = FqName("java.lang.Class") @@ -225,12 +224,12 @@ class JavaTypeResolver( } RawSubstitution.computeProjection(parameter, attr, erasedUpperBound) - }.toReadOnlyList() + }.toList() } if (typeParameters.size != javaType.typeArguments.size) { // Most of the time this means there is an error in the Java code - return typeParameters.map { p -> TypeProjectionImpl(ErrorUtils.createErrorType(p.name.asString())) }.toReadOnlyList() + return typeParameters.map { p -> TypeProjectionImpl(ErrorUtils.createErrorType(p.name.asString())) }.toList() } val howTheProjectionIsUsed = if (attr.howThisTypeIsUsed == SUPERTYPE) SUPERTYPE_ARGUMENT else TYPE_ARGUMENT return javaType.typeArguments.withIndex().map { @@ -243,7 +242,7 @@ class JavaTypeResolver( val parameter = typeParameters[i] transformToTypeProjection(javaTypeArgument, howTheProjectionIsUsed.toAttributes(), parameter) - }.toReadOnlyList() + }.toList() } private fun transformToTypeProjection( diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/propertiesConventionUtil.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/propertiesConventionUtil.kt index 11b90e70e39..595c653b6bc 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/propertiesConventionUtil.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/propertiesConventionUtil.kt @@ -18,7 +18,6 @@ package org.jetbrains.kotlin.load.java import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeSmart -import org.jetbrains.kotlin.utils.singletonOrEmptyList import org.jetbrains.kotlin.load.java.BuiltinSpecialProperties.getPropertyNameCandidatesBySpecialGetterName @@ -53,7 +52,7 @@ fun getPropertyNamesCandidatesByAccessorName(name: Name): List { val nameAsString = name.asString() if (JvmAbi.isGetterName(nameAsString)) { - return propertyNameByGetMethodName(name).singletonOrEmptyList() + return listOfNotNull(propertyNameByGetMethodName(name)) } if (JvmAbi.isSetterName(nameAsString)) { diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/typeEnhancement/typeEnhancement.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/typeEnhancement/typeEnhancement.kt index ae8d9af53d7..0322056bccd 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/typeEnhancement/typeEnhancement.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/typeEnhancement/typeEnhancement.kt @@ -33,8 +33,6 @@ import org.jetbrains.kotlin.platform.JavaToKotlinClassMap import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.createProjection import org.jetbrains.kotlin.types.typeUtil.isTypeParameter -import org.jetbrains.kotlin.utils.addToStdlib.check -import org.jetbrains.kotlin.utils.toReadOnlyList // The index in the lambda is the position of the type component: // Example: for `A>`, indices go as follows: `0 - A<...>, 1 - B, 2 - C, 3 - D, 4 - E`, @@ -52,7 +50,7 @@ private enum class TypeComponentPosition { } private open class Result(open val type: KotlinType, val subtreeSize: Int, val wereChanges: Boolean) { - val typeIfChanged: KotlinType? get() = type.check { wereChanges } + val typeIfChanged: KotlinType? get() = type.takeIf { wereChanges } } private class SimpleResult(override val type: SimpleType, subtreeSize: Int, wereChanges: Boolean): Result(type, subtreeSize, wereChanges) @@ -143,7 +141,7 @@ private fun SimpleType.enhanceInflexible(qualifiers: (Int) -> JavaTypeQualifiers private fun List.compositeAnnotationsOrSingle() = when (size) { 0 -> error("At least one Annotations object expected") 1 -> single() - else -> CompositeAnnotations(this.toReadOnlyList()) + else -> CompositeAnnotations(this.toList()) } private fun TypeComponentPosition.shouldEnhance() = this != TypeComponentPosition.INFLEXIBLE diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/AbstractBinaryClassAnnotationAndConstantLoader.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/AbstractBinaryClassAnnotationAndConstantLoader.kt index 3e0e8165537..b8d44542e15 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/AbstractBinaryClassAnnotationAndConstantLoader.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/AbstractBinaryClassAnnotationAndConstantLoader.kt @@ -167,7 +167,7 @@ abstract class AbstractBinaryClassAnnotationAndConstantLoader 1 else -> 0 } - else -> throw UnsupportedOperationException("Unsupported message: ${message.javaClass}") + else -> throw UnsupportedOperationException("Unsupported message: ${message::class.java}") } } diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/JvmBuiltInsSettings.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/JvmBuiltInsSettings.kt index 52b0c61742e..9ded7dd1f0f 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/JvmBuiltInsSettings.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/JvmBuiltInsSettings.kt @@ -47,7 +47,6 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.LazyWrappedType import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.SmartSet -import org.jetbrains.kotlin.utils.addToStdlib.check import java.io.Serializable import java.util.* @@ -263,7 +262,7 @@ open class JvmBuiltInsSettings( // No additional members should be added to Any if (isAny) return null - val fqName = fqNameUnsafe.check { it.isSafe }?.toSafe() ?: return null + val fqName = fqNameUnsafe.takeIf { it.isSafe }?.toSafe() ?: return null val javaAnalogueFqName = j2kClassMap.mapKotlinToJava(fqName.toUnsafe())?.asSingleFqName() ?: return null return ownerModuleDescriptor.resolveClassByFqName(javaAnalogueFqName, NoLookupLocation.FROM_BUILTINS) as? LazyJavaClassDescriptor diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/UnsafeVarianceTypeSubstitution.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/UnsafeVarianceTypeSubstitution.kt index be16970264f..7cc7b8030ce 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/UnsafeVarianceTypeSubstitution.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/UnsafeVarianceTypeSubstitution.kt @@ -32,7 +32,7 @@ internal class UnsafeVarianceTypeSubstitution(kotlinBuiltIns: KotlinBuiltIns) : val unsafeVariancePaths = mutableListOf>() IndexedTypeHolder(topLevelType).checkTypePosition( position, - { typeParameter, indexedTypeHolder, errorPosition -> + { _, indexedTypeHolder, _ -> unsafeVariancePaths.add(indexedTypeHolder.argumentIndices) }, customVariance = { null }) diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/serialization/jvm/JvmProtoBufUtil.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/serialization/jvm/JvmProtoBufUtil.kt index 3dc9993d110..81c95bce0ac 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/serialization/jvm/JvmProtoBufUtil.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/serialization/jvm/JvmProtoBufUtil.kt @@ -22,7 +22,6 @@ import org.jetbrains.kotlin.serialization.ClassData import org.jetbrains.kotlin.serialization.PackageData import org.jetbrains.kotlin.serialization.ProtoBuf import org.jetbrains.kotlin.serialization.deserialization.* -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.io.ByteArrayInputStream object JvmProtoBufUtil { @@ -65,7 +64,7 @@ object JvmProtoBufUtil { nameResolver.getString(signature.desc) } else { - val parameterTypes = proto.receiverType(typeTable).singletonOrEmptyList() + proto.valueParameterList.map { it.type(typeTable) } + val parameterTypes = listOfNotNull(proto.receiverType(typeTable)) + proto.valueParameterList.map { it.type(typeTable) } val parametersDesc = parameterTypes.map { mapTypeDefault(it, nameResolver) ?: return null } val returnTypeDesc = mapTypeDefault(proto.returnType(typeTable), nameResolver) ?: return null diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/components/RuntimeSourceElementFactory.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/components/RuntimeSourceElementFactory.kt index 422691f57dd..6c9ff43d35e 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/components/RuntimeSourceElementFactory.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/components/RuntimeSourceElementFactory.kt @@ -24,7 +24,7 @@ import org.jetbrains.kotlin.load.java.structure.reflect.ReflectJavaElement object RuntimeSourceElementFactory : JavaSourceElementFactory { class RuntimeSourceElement(override val javaElement: ReflectJavaElement) : JavaSourceElement { - override fun toString() = javaClass.name + ": " + javaElement.toString() + override fun toString() = this::class.java.name + ": " + javaElement.toString() override fun getContainingFile(): SourceFile = SourceFile.NO_SOURCE_FILE } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotation.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotation.kt index e14201627a8..ee27ba559a4 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotation.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotation.kt @@ -36,5 +36,5 @@ class ReflectJavaAnnotation(val annotation: Annotation) : ReflectJavaElement(), override fun hashCode() = annotation.hashCode() - override fun toString() = javaClass.name + ": " + annotation + override fun toString() = this::class.java.name + ": " + annotation } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotationArguments.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotationArguments.kt index 28eaf13626d..e6d8b757f07 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotationArguments.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaAnnotationArguments.kt @@ -25,7 +25,7 @@ abstract class ReflectJavaAnnotationArgument( companion object Factory { fun create(value: Any, name: Name?): ReflectJavaAnnotationArgument { return when { - value.javaClass.isEnumClassOrSpecializedEnumEntryClass() -> ReflectJavaEnumValueAnnotationArgument(name, value as Enum<*>) + value::class.java.isEnumClassOrSpecializedEnumEntryClass() -> ReflectJavaEnumValueAnnotationArgument(name, value as Enum<*>) value is Annotation -> ReflectJavaAnnotationAsAnnotationArgument(name, value) value is Array<*> -> ReflectJavaArrayAnnotationArgument(name, value) value is Class<*> -> ReflectJavaClassObjectAnnotationArgument(name, value) @@ -52,7 +52,7 @@ class ReflectJavaEnumValueAnnotationArgument( private val value: Enum<*> ) : ReflectJavaAnnotationArgument(name), JavaEnumValueAnnotationArgument { override fun resolve(): ReflectJavaField { - val clazz = value.javaClass + val clazz = value::class.java val enumClass = if (clazz.isEnum) clazz else clazz.enclosingClass return ReflectJavaField(enumClass.getDeclaredField(value.name)) } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaArrayType.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaArrayType.kt index 9babd0bb640..e636afa30d8 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaArrayType.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaArrayType.kt @@ -25,7 +25,7 @@ class ReflectJavaArrayType(override val reflectType: Type) : ReflectJavaType(), when { this is GenericArrayType -> ReflectJavaType.create(genericComponentType) this is Class<*> && isArray() -> ReflectJavaType.create(getComponentType()) - else -> throw IllegalArgumentException("Not an array type (${reflectType.javaClass}): $reflectType") + else -> throw IllegalArgumentException("Not an array type (${reflectType::class.java}): $reflectType") } } } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClass.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClass.kt index 1bde0358b05..969509d95cd 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClass.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClass.kt @@ -110,5 +110,5 @@ class ReflectJavaClass( override fun hashCode() = klass.hashCode() - override fun toString() = javaClass.name + ": " + klass + override fun toString() = this::class.java.name + ": " + klass } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClassifierType.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClassifierType.kt index eb2d0508678..da948d81524 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClassifierType.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaClassifierType.kt @@ -32,7 +32,7 @@ class ReflectJavaClassifierType(public override val reflectType: Type) : Reflect is Class<*> -> ReflectJavaClass(type) is TypeVariable<*> -> ReflectJavaTypeParameter(type) is ParameterizedType -> ReflectJavaClass(type.rawType as Class<*>) - else -> throw IllegalStateException("Not a classifier type (${type.javaClass}): $type") + else -> throw IllegalStateException("Not a classifier type (${type::class.java}): $type") } classifier } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaMember.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaMember.kt index bf2a20de76e..a12164f44ad 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaMember.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaMember.kt @@ -59,7 +59,7 @@ abstract class ReflectJavaMember : ReflectJavaElement(), ReflectJavaAnnotationOw override fun hashCode() = member.hashCode() - override fun toString() = javaClass.name + ": " + member + override fun toString() = this::class.java.name + ": " + member } private object Java8ParameterNamesLoader { @@ -69,7 +69,7 @@ private object Java8ParameterNamesLoader { fun buildCache(member: Member): Cache { // This should be either j.l.reflect.Method or j.l.reflect.Constructor - val methodOrConstructorClass = member.javaClass + val methodOrConstructorClass = member::class.java val getParameters = try { methodOrConstructorClass.getMethod("getParameters") diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaPackage.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaPackage.kt index 6da7fcbe066..090b2dc60da 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaPackage.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaPackage.kt @@ -37,5 +37,5 @@ class ReflectJavaPackage(override val fqName: FqName) : ReflectJavaElement(), Ja override fun hashCode() = fqName.hashCode() - override fun toString() = javaClass.name + ": " + fqName + override fun toString() = this::class.java.name + ": " + fqName } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaType.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaType.kt index 771a5d7ac71..81c59f64551 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaType.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaType.kt @@ -39,5 +39,5 @@ abstract class ReflectJavaType : JavaType { override fun hashCode() = reflectType.hashCode() - override fun toString() = javaClass.name + ": " + reflectType + override fun toString() = this::class.java.name + ": " + reflectType } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaTypeParameter.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaTypeParameter.kt index 2004bfd206e..727aa1f75ab 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaTypeParameter.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaTypeParameter.kt @@ -42,5 +42,5 @@ class ReflectJavaTypeParameter( override fun hashCode() = typeVariable.hashCode() - override fun toString() = javaClass.name + ": " + typeVariable + override fun toString() = this::class.java.name + ": " + typeVariable } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaValueParameter.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaValueParameter.kt index f46651d3d29..5b2321a148f 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaValueParameter.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/ReflectJavaValueParameter.kt @@ -38,5 +38,5 @@ class ReflectJavaValueParameter( override val name: Name? get() = reflectName?.let(Name::guessByFirstCharacter) - override fun toString() = javaClass.name + ": " + (if (isVararg) "vararg " else "") + name + ": " + type + override fun toString() = this::class.java.name + ": " + (if (isVararg) "vararg " else "") + name + ": " + type } diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/reflectClassUtil.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/reflectClassUtil.kt index b7512b13cb7..04b4df25e13 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/reflectClassUtil.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/java/structure/reflect/reflectClassUtil.kt @@ -75,7 +75,7 @@ val Class<*>.desc: String } fun Class<*>.createArrayType(): Class<*> = - Array.newInstance(this, 0).javaClass + Array.newInstance(this, 0)::class.java /** * @return all arguments of a parameterized type, including those of outer classes in case this type represents an inner generic. diff --git a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/kotlin/reflect/ReflectKotlinClass.kt b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/kotlin/reflect/ReflectKotlinClass.kt index 0e499913e27..ebda9975bed 100644 --- a/core/descriptors.runtime/src/org/jetbrains/kotlin/load/kotlin/reflect/ReflectKotlinClass.kt +++ b/core/descriptors.runtime/src/org/jetbrains/kotlin/load/kotlin/reflect/ReflectKotlinClass.kt @@ -72,7 +72,7 @@ class ReflectKotlinClass private constructor( override fun hashCode() = klass.hashCode() - override fun toString() = javaClass.name + ": " + klass + override fun toString() = this::class.java.name + ": " + klass } private object ReflectClassStructure { @@ -175,7 +175,7 @@ private object ReflectClassStructure { } private fun processAnnotationArgumentValue(visitor: KotlinJvmBinaryClass.AnnotationArgumentVisitor, name: Name, value: Any) { - val clazz = value.javaClass + val clazz = value::class.java when { clazz in TYPES_ELIGIBLE_FOR_SIMPLE_VISIT -> { visitor.visit(name, value) diff --git a/core/descriptors/src/org/jetbrains/kotlin/builtins/functionTypes.kt b/core/descriptors/src/org/jetbrains/kotlin/builtins/functionTypes.kt index 9094cdb98f9..81d7c4e1ea5 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/builtins/functionTypes.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/builtins/functionTypes.kt @@ -38,7 +38,6 @@ import org.jetbrains.kotlin.types.typeUtil.asTypeProjection import org.jetbrains.kotlin.types.typeUtil.replaceAnnotations import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* private fun KotlinType.isTypeOrSubtypeOf(predicate: (KotlinType) -> Boolean): Boolean = @@ -150,7 +149,7 @@ fun KotlinType.extractParameterNameFromFunctionTypeArgument(): Name? { val annotation = annotations.findAnnotation(KotlinBuiltIns.FQ_NAMES.parameterName) ?: return null val name = (annotation.allValueArguments.values.singleOrNull() as? StringValue) ?.value - ?.check { Name.isValidIdentifier(it) } + ?.takeIf { Name.isValidIdentifier(it) } ?: return null return Name.identifier(name) } @@ -167,7 +166,7 @@ fun getFunctionTypeArgumentProjections( arguments.addIfNotNull(receiverType?.asTypeProjection()) parameterTypes.mapIndexedTo(arguments) { index, type -> - val name = parameterNames?.get(index)?.check { !it.isSpecial } + val name = parameterNames?.get(index)?.takeIf { !it.isSpecial } val typeToUse = if (name != null) { val annotationClass = builtIns.getBuiltInClassByName(KotlinBuiltIns.FQ_NAMES.parameterName.shortName()) val nameValue = ConstantValueFactory(builtIns).createStringValue(name.asString()) diff --git a/core/descriptors/src/org/jetbrains/kotlin/builtins/functions/FunctionClassDescriptor.kt b/core/descriptors/src/org/jetbrains/kotlin/builtins/functions/FunctionClassDescriptor.kt index b32586b3065..116f6a0f1d1 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/builtins/functions/FunctionClassDescriptor.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/builtins/functions/FunctionClassDescriptor.kt @@ -30,7 +30,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.* -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* /** @@ -81,7 +80,7 @@ class FunctionClassDescriptor( typeParameter(Variance.OUT_VARIANCE, "R") - parameters = result.toReadOnlyList() + parameters = result.toList() } override fun getContainingDeclaration() = containingDeclaration @@ -146,7 +145,7 @@ class FunctionClassDescriptor( add(kotlinPackageFragment, Kind.Function.numberedClassName(arity)) } - return result.toReadOnlyList() + return result.toList() } override fun getParameters() = this@FunctionClassDescriptor.parameters diff --git a/core/descriptors/src/org/jetbrains/kotlin/descriptors/VariableDescriptorWithAccessors.kt b/core/descriptors/src/org/jetbrains/kotlin/descriptors/VariableDescriptorWithAccessors.kt index e946cdc64e7..5008a327615 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/descriptors/VariableDescriptorWithAccessors.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/descriptors/VariableDescriptorWithAccessors.kt @@ -16,8 +16,6 @@ package org.jetbrains.kotlin.descriptors -import org.jetbrains.kotlin.utils.singletonOrEmptyList - interface VariableDescriptorWithAccessors : VariableDescriptor { val getter: VariableAccessorDescriptor? @@ -35,4 +33,4 @@ interface VariableDescriptorWithAccessors : VariableDescriptor { } val VariableDescriptorWithAccessors.accessors: List - get() = getter.singletonOrEmptyList() + setter.singletonOrEmptyList() + get() = listOfNotNull(getter) + listOfNotNull(setter) diff --git a/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/CompositePackageFragmentProvider.kt b/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/CompositePackageFragmentProvider.kt index de3eab32b01..50298ddd906 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/CompositePackageFragmentProvider.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/CompositePackageFragmentProvider.kt @@ -21,7 +21,6 @@ import org.jetbrains.kotlin.descriptors.PackageFragmentProvider import org.jetbrains.kotlin.name.FqName import java.util.* import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.utils.toReadOnlyList class CompositePackageFragmentProvider(// can be modified from outside private val providers: List) : PackageFragmentProvider { @@ -31,7 +30,7 @@ class CompositePackageFragmentProvider(// can be modified from outside for (provider in providers) { result.addAll(provider.getPackageFragments(fqName)) } - return result.toReadOnlyList() + return result.toList() } override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection { diff --git a/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/SubpackagesScope.kt b/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/SubpackagesScope.kt index 791037a23d2..643254d7d70 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/SubpackagesScope.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/descriptors/impl/SubpackagesScope.kt @@ -58,7 +58,7 @@ open class SubpackagesScope(private val moduleDescriptor: ModuleDescriptor, priv } override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.popIndent() diff --git a/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererImpl.kt b/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererImpl.kt index 3b07163553d..bbdccb3bf22 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererImpl.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererImpl.kt @@ -282,7 +282,7 @@ internal class DescriptorRendererImpl( return when (cd) { is TypeParameterDescriptor, is ClassDescriptor, is TypeAliasDescriptor -> renderClassifierName(cd) null -> typeConstructor.toString() - else -> error("Unexpected classifier: " + cd.javaClass) + else -> error("Unexpected classifier: " + cd::class.java) } } diff --git a/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererOptionsImpl.kt b/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererOptionsImpl.kt index 1d3d83d9ab7..9cace3597b4 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererOptionsImpl.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/renderer/DescriptorRendererOptionsImpl.kt @@ -38,7 +38,7 @@ internal class DescriptorRendererOptionsImpl : DescriptorRendererOptions { val copy = DescriptorRendererOptionsImpl() //TODO: use Kotlin reflection - for (field in this.javaClass.declaredFields) { + for (field in this::class.java.declaredFields) { if (field.modifiers.and(Modifier.STATIC) != 0) continue field.isAccessible = true val property = field.get(this) as? ObservableProperty<*> ?: continue @@ -54,7 +54,7 @@ internal class DescriptorRendererOptionsImpl : DescriptorRendererOptions { } private fun property(initialValue: T): ReadWriteProperty { - return Delegates.vetoable(initialValue) { property, oldValue, newValue -> + return Delegates.vetoable(initialValue) { _, _, _ -> if (isLocked) { throw IllegalStateException("Cannot modify readonly DescriptorRendererOptions") } diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorEquivalenceForOverrides.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorEquivalenceForOverrides.kt index 3d33a21361d..6b3d479b483 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorEquivalenceForOverrides.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorEquivalenceForOverrides.kt @@ -47,7 +47,7 @@ object DescriptorEquivalenceForOverrides { private fun areTypeParametersEquivalent( a: TypeParameterDescriptor, b: TypeParameterDescriptor, - equivalentCallables: (DeclarationDescriptor?, DeclarationDescriptor?) -> Boolean = {x, y -> false} + equivalentCallables: (DeclarationDescriptor?, DeclarationDescriptor?) -> Boolean = { _, _ -> false} ): Boolean { if (a == b) return true if (a.containingDeclaration == b.containingDeclaration) return false @@ -69,7 +69,7 @@ object DescriptorEquivalenceForOverrides { // Distinct locals are not equivalent if (DescriptorUtils.isLocal(a) || DescriptorUtils.isLocal(b)) return false - if (!ownersEquivalent(a, b, {x, y -> false})) return false + if (!ownersEquivalent(a, b, { _, _ -> false})) return false val overridingUtil = OverridingUtil.createWithEqualityAxioms eq@ { c1, c2 -> diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.kt index 2d344b98039..f39d4ea5180 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/DescriptorUtils.kt @@ -39,7 +39,6 @@ import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.SmartList -import org.jetbrains.kotlin.utils.addToStdlib.check fun ClassDescriptor.getClassObjectReferenceTarget(): ClassDescriptor = companionObjectDescriptor ?: this @@ -228,7 +227,7 @@ val DeclarationDescriptor.parents: Sequence val CallableMemberDescriptor.propertyIfAccessor: CallableMemberDescriptor get() = if (this is PropertyAccessorDescriptor) correspondingProperty else this -fun CallableDescriptor.fqNameOrNull(): FqName? = fqNameUnsafe.check { it.isSafe }?.toSafe() +fun CallableDescriptor.fqNameOrNull(): FqName? = fqNameUnsafe.takeIf { it.isSafe }?.toSafe() fun CallableMemberDescriptor.firstOverridden( useOriginal: Boolean = false, diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/constants/constantValues.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/constants/constantValues.kt index 480b2d0a8b5..26c312f834a 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/constants/constantValues.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/constants/constantValues.kt @@ -61,7 +61,7 @@ class ArrayValue( override fun equals(other: Any?): Boolean { if (this === other) return true - if (javaClass != other?.javaClass) return false + if (other == null || other::class.java != this::class.java) return false return value == (other as ArrayValue).value } @@ -149,7 +149,7 @@ class EnumValue( override fun equals(other: Any?): Boolean { if (this === other) return true - if (javaClass != other?.javaClass) return false + if (other == null || other::class.java != this::class.java) return false return value == (other as EnumValue).value } @@ -201,7 +201,7 @@ class IntValue( override fun equals(other: Any?): Boolean { if (this === other) return true - if (javaClass != other?.javaClass) return false + if (other == null || other::class.java != this::class.java) return false val intValue = other as IntValue @@ -266,7 +266,7 @@ class StringValue( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other == null || javaClass != other.javaClass) return false + if (other == null || other::class.java != this::class.java) return false return value != (other as StringValue).value } diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt index 076750b7a7a..a23eed6efdd 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt @@ -57,7 +57,7 @@ abstract class AbstractScopeAdapter : MemberScope { override fun getVariableNames() = workerScope.getVariableNames() override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.print("worker =") diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedMemberScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedMemberScope.kt index c085613d6ab..8357efafd05 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedMemberScope.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedMemberScope.kt @@ -47,7 +47,7 @@ class ChainedMemberScope( override fun toString() = debugName override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, ": ", debugName, " {") + p.println(this::class.java.simpleName, ": ", debugName, " {") p.pushIndent() for (scope in scopes) { diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/MemberScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/MemberScope.kt index 14b5f193e91..7666365671f 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/MemberScope.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/MemberScope.kt @@ -20,7 +20,6 @@ import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.utils.Printer -import org.jetbrains.kotlin.utils.toReadOnlyList import java.lang.reflect.Modifier interface MemberScope : ResolutionScope { @@ -157,7 +156,7 @@ class DescriptorKindFilter( val filter = field.get(null) as? DescriptorKindFilter if (filter != null) MaskToName(filter.kindMask, field.name) else null } - .toReadOnlyList() + .toList() private val DEBUG_MASK_BIT_NAMES = staticFields() .filter { it.type == Integer.TYPE } @@ -166,7 +165,7 @@ class DescriptorKindFilter( val isOneBitMask = mask == (mask and (-mask)) if (isOneBitMask) MaskToName(mask, field.name) else null } - .toReadOnlyList() + .toList() private inline fun staticFields() = T::class.java.fields.filter { Modifier.isStatic(it.modifiers) } } @@ -181,7 +180,7 @@ abstract class DescriptorKindExclude { */ abstract val fullyExcludedDescriptorKinds: Int - override fun toString() = this.javaClass.simpleName + override fun toString() = this::class.java.simpleName object Extensions : DescriptorKindExclude() { override fun excludes(descriptor: DeclarationDescriptor) diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt index 7f290b61668..a101697f1dc 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt @@ -79,7 +79,7 @@ class SubstitutingScope(private val workerScope: MemberScope, givenSubstitutor: override fun getVariableNames() = workerScope.getVariableNames() override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.println("substitutor = ") diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewCapturedType.kt b/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewCapturedType.kt index be7fa79e487..b1b7da1171e 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewCapturedType.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewCapturedType.kt @@ -34,9 +34,9 @@ fun captureFromArguments( val arguments = type.arguments if (arguments.all { it.projectionKind == Variance.INVARIANT }) return type - val newArguments = arguments.mapIndexed { - index, projection -> - if (projection.projectionKind == Variance.INVARIANT) return@mapIndexed projection + val newArguments = arguments.map { + projection -> + if (projection.projectionKind == Variance.INVARIANT) return@map projection val lowerType = if (!projection.isStarProjection && projection.projectionKind == Variance.IN_VARIANCE) { projection.type.unwrap() diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt b/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt index 1ed8d58d4c2..74cd928d7dc 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt @@ -27,7 +27,6 @@ import org.jetbrains.kotlin.types.checker.TypeCheckerContext.SupertypesPolicy import org.jetbrains.kotlin.types.typeUtil.asTypeProjection import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.SmartList -import org.jetbrains.kotlin.utils.addToStdlib.check object StrictEqualityTypeChecker { /** @@ -106,7 +105,7 @@ object NewKotlinTypeChecker : KotlinTypeChecker { when (constructor) { // Type itself can be just SimpleTypeImpl, not CapturedType. see KT-16147 is CapturedTypeConstructor -> { - val lowerType = constructor.typeProjection.check { it.projectionKind == Variance.IN_VARIANCE }?.type?.unwrap() + val lowerType = constructor.typeProjection.takeIf { it.projectionKind == Variance.IN_VARIANCE }?.type?.unwrap() // it is incorrect calculate this type directly because of recursive star projections if (constructor.newTypeConstructor == null) { @@ -191,9 +190,9 @@ object NewKotlinTypeChecker : KotlinTypeChecker { else -> { // at least 2 supertypes with same constructors. Such case is rare if (supertypesWithSameConstructor.any { isSubtypeForSameConstructor(it.arguments, superType) }) return true - val newArguments = superConstructor.parameters.mapIndexed { index, parameterDescriptor -> + val newArguments = superConstructor.parameters.mapIndexed { index, _ -> val allProjections = supertypesWithSameConstructor.map { - it.arguments.getOrNull(index)?.check { it.projectionKind == Variance.INVARIANT }?.type?.unwrap() + it.arguments.getOrNull(index)?.takeIf { it.projectionKind == Variance.INVARIANT }?.type?.unwrap() ?: error("Incorrect type: $it, subType: $subType, superType: $superType") } diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/checker/TypeCheckerContext.kt b/core/descriptors/src/org/jetbrains/kotlin/types/checker/TypeCheckerContext.kt index 2b310627ad3..607c1651dcf 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/types/checker/TypeCheckerContext.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/types/checker/TypeCheckerContext.kt @@ -18,7 +18,6 @@ package org.jetbrains.kotlin.types.checker import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.utils.SmartSet -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* open class TypeCheckerContext(val errorTypeEqualsToAnything: Boolean) { @@ -85,7 +84,7 @@ open class TypeCheckerContext(val errorTypeEqualsToAnything: Boolean) { return true } - val policy = supertypesPolicy(current).check { it != SupertypesPolicy.None } ?: continue + val policy = supertypesPolicy(current).takeIf { it != SupertypesPolicy.None } ?: continue for (supertype in current.constructor.supertypes) deque.add(policy.transformType(supertype)) } diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/checker/utils.kt b/core/descriptors/src/org/jetbrains/kotlin/types/checker/utils.kt index 3646b041b4f..c9105618594 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/types/checker/utils.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/types/checker/utils.kt @@ -90,12 +90,12 @@ private fun TypeConstructor.debugInfo() = buildString { + "type: ${this@debugInfo}" + "hashCode: ${this@debugInfo.hashCode()}" - + "javaClass: ${this@debugInfo.javaClass.canonicalName}" + + "javaClass: ${this@debugInfo::class.java.canonicalName}" var declarationDescriptor: DeclarationDescriptor? = declarationDescriptor while (declarationDescriptor != null) { + "fqName: ${DescriptorRenderer.FQ_NAMES_IN_TYPES.render(declarationDescriptor)}" - + "javaClass: ${declarationDescriptor.javaClass.canonicalName}" + + "javaClass: ${declarationDescriptor::class.java.canonicalName}" declarationDescriptor = declarationDescriptor.containingDeclaration } diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/AbstractDeserializedPackageFragmentProvider.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/AbstractDeserializedPackageFragmentProvider.kt index 4929388e278..ac06882990b 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/AbstractDeserializedPackageFragmentProvider.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/AbstractDeserializedPackageFragmentProvider.kt @@ -22,7 +22,6 @@ import org.jetbrains.kotlin.descriptors.PackageFragmentProvider import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.storage.StorageManager -import org.jetbrains.kotlin.utils.singletonOrEmptyList abstract class AbstractDeserializedPackageFragmentProvider( protected val storageManager: StorageManager, @@ -39,7 +38,7 @@ abstract class AbstractDeserializedPackageFragmentProvider( protected abstract fun findPackage(fqName: FqName): DeserializedPackageFragment? - override fun getPackageFragments(fqName: FqName): List = fragments(fqName).singletonOrEmptyList() + override fun getPackageFragments(fqName: FqName): List = listOfNotNull(fragments(fqName)) override fun getSubPackagesOf(fqName: FqName, nameFilter: (Name) -> Boolean): Collection = emptySet() } diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt index 16ad6ad4728..4994fdf68fc 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/MemberDeserializer.kt @@ -29,7 +29,6 @@ import org.jetbrains.kotlin.resolve.DescriptorFactory import org.jetbrains.kotlin.serialization.Flags import org.jetbrains.kotlin.serialization.ProtoBuf import org.jetbrains.kotlin.serialization.deserialization.descriptors.* -import org.jetbrains.kotlin.utils.toReadOnlyList class MemberDeserializer(private val c: DeserializationContext) { private val annotationDeserializer = AnnotationDeserializer(c.components.moduleDescriptor, c.components.notFoundClasses) @@ -267,7 +266,7 @@ class MemberDeserializer(private val c: DeserializationContext) { proto.varargElementType(c.typeTable)?.let { c.typeDeserializer.type(it) }, SourceElement.NO_SOURCE ) - }.toReadOnlyList() + }.toList() } private fun DeclarationDescriptor.asProtoContainer(): ProtoContainer? = when (this) { diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/ProtoContainer.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/ProtoContainer.kt index de299dd5c71..ac2ce0d02c8 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/ProtoContainer.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/ProtoContainer.kt @@ -53,5 +53,5 @@ sealed class ProtoContainer( abstract fun debugFqName(): FqName - override fun toString() = "${javaClass.simpleName}: ${debugFqName()}" + override fun toString() = "${this::class.java.simpleName}: ${debugFqName()}" } diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/TypeDeserializer.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/TypeDeserializer.kt index 6588724e940..62e7ba3581c 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/TypeDeserializer.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/TypeDeserializer.kt @@ -29,8 +29,6 @@ import org.jetbrains.kotlin.serialization.ProtoBuf import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedAnnotationsWithPossibleTargets import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedTypeParameterDescriptor import org.jetbrains.kotlin.types.* -import org.jetbrains.kotlin.utils.addToStdlib.check -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* class TypeDeserializer( @@ -60,7 +58,7 @@ class TypeDeserializer( } val ownTypeParameters: List - get() = typeParameterDescriptors.values.toReadOnlyList() + get() = typeParameterDescriptors.values.toList() // TODO: don't load identical types from TypeTable more than once fun type(proto: ProtoBuf.Type, additionalAnnotations: Annotations = Annotations.EMPTY): KotlinType { @@ -99,7 +97,7 @@ class TypeDeserializer( val arguments = proto.collectAllArguments().mapIndexed { index, proto -> typeArgument(constructor.parameters.getOrNull(index), proto) - }.toReadOnlyList() + }.toList() val simpleType = if (Flags.SUSPEND_TYPE.get(proto.flags)) { createSuspendFunctionType(annotations, constructor, arguments, proto.nullable) @@ -148,7 +146,7 @@ class TypeDeserializer( val result = when (functionTypeConstructor.parameters.size - arguments.size) { 0 -> { val functionType = KotlinTypeFactory.simpleType(annotations, functionTypeConstructor, arguments, nullable) - functionType.check { it.isFunctionType }?.let(::transformRuntimeFunctionTypeToSuspendFunction) + functionType.takeIf { it.isFunctionType }?.let(::transformRuntimeFunctionTypeToSuspendFunction) } // This case for types written by eap compiler 1.1 1 -> { diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedAnnotations.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedAnnotations.kt index 449c337157e..da442b3f191 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedAnnotations.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedAnnotations.kt @@ -23,7 +23,6 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.storage.StorageManager -import org.jetbrains.kotlin.utils.toReadOnlyList class DeserializedAnnotations( storageManager: StorageManager, @@ -36,7 +35,7 @@ open class DeserializedAnnotationsWithPossibleTargets( storageManager: StorageManager, compute: () -> List ) : Annotations { - private val annotations = storageManager.createLazyValue { compute().toReadOnlyList() } + private val annotations = storageManager.createLazyValue { compute().toList() } override fun isEmpty(): Boolean = annotations().isEmpty() diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt index 3104f9a8fac..57960ade25c 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt @@ -38,8 +38,6 @@ import org.jetbrains.kotlin.serialization.deserialization.* import org.jetbrains.kotlin.types.AbstractClassTypeConstructor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor -import org.jetbrains.kotlin.utils.singletonOrEmptyList -import org.jetbrains.kotlin.utils.toReadOnlyList import java.util.* class DeserializedClassDescriptor( @@ -127,7 +125,7 @@ class DeserializedClassDescriptor( override fun getUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor? = primaryConstructor() private fun computeConstructors(): Collection = - computeSecondaryConstructors() + unsubstitutedPrimaryConstructor.singletonOrEmptyList() + + computeSecondaryConstructors() + listOfNotNull(unsubstitutedPrimaryConstructor) + c.components.additionalClassPartsProvider.getConstructors(this) private fun computeSecondaryConstructors(): List = @@ -192,7 +190,7 @@ class DeserializedClassDescriptor( ) } - return result.toReadOnlyList() + return result.toList() } override fun getParameters() = parameters() diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt index ba654a2fc21..12718d200eb 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt @@ -227,7 +227,7 @@ abstract class DeserializedMemberScope protected constructor( protected abstract fun addEnumEntryDescriptors(result: MutableCollection, nameFilter: (Name) -> Boolean) override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName, " {") + p.println(this::class.java.simpleName, " {") p.pushIndent() p.println("containingDeclaration = " + c.containingDeclaration) diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/SinceKotlinInfo.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/SinceKotlinInfo.kt index d5e56bef54c..f210c0ee743 100644 --- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/SinceKotlinInfo.kt +++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/SinceKotlinInfo.kt @@ -97,7 +97,7 @@ class SinceKotlinInfo( is ProtoBuf.Function -> if (proto.hasSinceKotlinInfo()) proto.sinceKotlinInfo else return null is ProtoBuf.Property -> if (proto.hasSinceKotlinInfo()) proto.sinceKotlinInfo else return null is ProtoBuf.TypeAlias -> if (proto.hasSinceKotlinInfo()) proto.sinceKotlinInfo else return null - else -> throw IllegalStateException("Unexpected declaration: ${proto.javaClass}") + else -> throw IllegalStateException("Unexpected declaration: ${proto::class.java}") } val info = table[id] ?: return null diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt index b1f320fe469..33f93595d37 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/KDeclarationContainerImpl.kt @@ -24,7 +24,6 @@ import org.jetbrains.kotlin.load.java.structure.reflect.safeClassLoader import org.jetbrains.kotlin.load.kotlin.reflect.RuntimeModuleData import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.scopes.MemberScope -import org.jetbrains.kotlin.utils.toReadOnlyList import java.lang.reflect.Constructor import java.lang.reflect.Method import java.util.* @@ -65,7 +64,7 @@ internal abstract class KDeclarationContainerImpl : ClassBasedDeclarationContain belonginess.accept(descriptor)) descriptor.accept(visitor, Unit) else null - }.toReadOnlyList() + }.toList() } protected enum class MemberBelonginess { diff --git a/core/util.runtime/src/org/jetbrains/kotlin/serialization/deserialization/BinaryVersion.kt b/core/util.runtime/src/org/jetbrains/kotlin/serialization/deserialization/BinaryVersion.kt index 70e892c0a72..4020b8a1b27 100644 --- a/core/util.runtime/src/org/jetbrains/kotlin/serialization/deserialization/BinaryVersion.kt +++ b/core/util.runtime/src/org/jetbrains/kotlin/serialization/deserialization/BinaryVersion.kt @@ -52,7 +52,8 @@ abstract class BinaryVersion(vararg val numbers: Int) { } override fun equals(other: Any?) = - this.javaClass == other?.javaClass && + other != null && + this::class.java == other::class.java && major == (other as BinaryVersion).major && minor == other.minor && patch == other.patch && rest == other.rest override fun hashCode(): Int{ diff --git a/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt b/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt index 4c32e44173c..46095653edd 100644 --- a/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt +++ b/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt @@ -92,7 +92,7 @@ fun constant(calculator: () -> T): T { if (cached != null) return cached as T // safety check - val fields = calculator.javaClass.declaredFields.filter { it.modifiers.and(Modifier.STATIC) == 0 } + val fields = calculator::class.java.declaredFields.filter { it.modifiers.and(Modifier.STATIC) == 0 } assert(fields.isEmpty()) { "No fields in the passed lambda expected but ${fields.joinToString()} found" } diff --git a/core/util.runtime/src/org/jetbrains/kotlin/utils/functions.kt b/core/util.runtime/src/org/jetbrains/kotlin/utils/functions.kt index 8b720b882e5..4e067b5e4cd 100644 --- a/core/util.runtime/src/org/jetbrains/kotlin/utils/functions.kt +++ b/core/util.runtime/src/org/jetbrains/kotlin/utils/functions.kt @@ -31,7 +31,7 @@ private val ALWAYS_NULL: (Any?) -> Any? = { null } fun alwaysNull(): (T) -> R? = ALWAYS_NULL as (T) -> R? val DO_NOTHING: (Any?) -> Unit = { } -val DO_NOTHING_2: (Any?, Any?) -> Unit = { x, y -> } -val DO_NOTHING_3: (Any?, Any?, Any?) -> Unit = { x, y, z -> } +val DO_NOTHING_2: (Any?, Any?) -> Unit = { _, _ -> } +val DO_NOTHING_3: (Any?, Any?, Any?) -> Unit = { _, _, _ -> } fun doNothing(): (T) -> Unit = DO_NOTHING diff --git a/eval4j/src/org/jetbrains/eval4j/interpreterLoop.kt b/eval4j/src/org/jetbrains/eval4j/interpreterLoop.kt index 8e29e1d7dd1..f3ba9639a70 100644 --- a/eval4j/src/org/jetbrains/eval4j/interpreterLoop.kt +++ b/eval4j/src/org/jetbrains/eval4j/interpreterLoop.kt @@ -120,7 +120,7 @@ fun interpreterLoop( return exceptionCaught(exceptionValue) { exceptionType -> try { - val exceptionClass = exception.javaClass + val exceptionClass = exception::class.java val _class = Class.forName( exceptionType.internalName.replace('/', '.'), true, @@ -222,7 +222,7 @@ fun interpreterLoop( } catch (e: ThrownFromEvalExceptionBase) { val exception = e.cause!! - val exceptionValue = ObjectValue(exception, Type.getType(exception.javaClass)) + val exceptionValue = ObjectValue(exception, Type.getType(exception::class.java)) val handled = handler.exceptionThrown(frame, currentInsn, exceptionValue) if (handled != null) return handled diff --git a/eval4j/src/org/jetbrains/eval4j/jdi/jdiValues.kt b/eval4j/src/org/jetbrains/eval4j/jdi/jdiValues.kt index 149a79891d3..78d89672a3c 100644 --- a/eval4j/src/org/jetbrains/eval4j/jdi/jdiValues.kt +++ b/eval4j/src/org/jetbrains/eval4j/jdi/jdiValues.kt @@ -48,7 +48,7 @@ fun makeInitialFrame(methodNode: MethodNode, arguments: List): Frame { val value = JArray.get(arr, ind) - if (value == null) NULL_VALUE else ObjectValue(value, Type.getType(value.javaClass)) + if (value == null) NULL_VALUE else ObjectValue(value, Type.getType(value::class.java)) } else -> throw UnsupportedOperationException("Unsupported array element type: $elementType") } @@ -204,7 +204,7 @@ object REFLECTION_EVAL : Eval { } } catch (e: Throwable) { - throw ThrownFromEvaluatedCodeException(ObjectValue(e, Type.getType(e.javaClass))) + throw ThrownFromEvaluatedCodeException(ObjectValue(e, Type.getType(e::class.java))) } } @@ -262,7 +262,7 @@ object REFLECTION_EVAL : Eval { } fun findInstanceField(obj: Any, fieldDesc: FieldDescription): Field { - val _class = obj.javaClass + val _class = obj::class.java val field = _class.findField(fieldDesc) assertNotNull("Field not found: $fieldDesc", field) return field!! @@ -287,7 +287,7 @@ object REFLECTION_EVAL : Eval { } } val obj = instance.obj().checkNull() - val method = obj.javaClass.findMethod(methodDesc) + val method = obj::class.java.findMethod(methodDesc) assertNotNull("Method not found: $methodDesc", method) val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray() val result = mayThrow {method!!.invoke(obj, *args)} @@ -322,7 +322,7 @@ class ReflectionLookup(val classLoader: ClassLoader) { } @Suppress("UNCHECKED_CAST") -fun Class.findMethod(methodDesc: MethodDescription): Method? { +fun Class.findMethod(methodDesc: MethodDescription): Method? { for (declared in declaredMethods) { if (methodDesc.matches(declared)) return declared } @@ -369,7 +369,7 @@ fun MethodDescription.matches(method: Method): Boolean { } @Suppress("UNCHECKED_CAST") -fun Class.findField(fieldDesc: FieldDescription): Field? { +fun Class.findField(fieldDesc: FieldDescription): Field? { for (declared in declaredFields) { if (fieldDesc.matches(declared)) return declared } diff --git a/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt b/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt index 0e12c80196c..6afb50f8a76 100644 --- a/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt +++ b/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt @@ -80,7 +80,7 @@ private fun buildTestCase(ownerClass: Class, } catch (e: Throwable) { val cause = e.cause ?: e - expected = ExceptionThrown(objectToValue(cause, Type.getType(cause.javaClass)) as ObjectValue, ExceptionThrown.ExceptionKind.FROM_EVALUATOR) + expected = ExceptionThrown(objectToValue(cause, Type.getType(cause::class.java)) as ObjectValue, ExceptionThrown.ExceptionKind.FROM_EVALUATOR) } } } diff --git a/generators/tests/org/jetbrains/kotlin/generators/protobuf/ProtoBufConsistencyTest.kt b/generators/tests/org/jetbrains/kotlin/generators/protobuf/ProtoBufConsistencyTest.kt index f8cf88dc834..9cfe1a3072d 100644 --- a/generators/tests/org/jetbrains/kotlin/generators/protobuf/ProtoBufConsistencyTest.kt +++ b/generators/tests/org/jetbrains/kotlin/generators/protobuf/ProtoBufConsistencyTest.kt @@ -31,7 +31,7 @@ class ProtoBufConsistencyTest : TestCase() { for (protoPath in PROTO_PATHS) { val classFqName = protoPath.packageName + "." + protoPath.debugClassName - val klass = javaClass.classLoader.loadClass(classFqName) ?: error("Class not found: $classFqName") + val klass = this::class.java.classLoader.loadClass(classFqName) ?: error("Class not found: $classFqName") for (field in klass.declaredFields) { if (Modifier.isStatic(field.modifiers) && field.type == GeneratedExtension::class.java) { // The only place where type information for an extension is stored is the field's declared generic type. diff --git a/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/SyntheticKotlinBlock.kt b/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/SyntheticKotlinBlock.kt index 960b7fbd0d9..3c81058b0fa 100644 --- a/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/SyntheticKotlinBlock.kt +++ b/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/SyntheticKotlinBlock.kt @@ -78,6 +78,6 @@ class SyntheticKotlinBlock( } } - return javaClass.name + ": " + textRange + return this::class.java.name + ": " + textRange } } \ No newline at end of file diff --git a/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/kotlinSpacingRules.kt b/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/kotlinSpacingRules.kt index 7e461b7dbf6..55716ea2be6 100644 --- a/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/kotlinSpacingRules.kt +++ b/idea/formatter/src/org/jetbrains/kotlin/idea/formatter/kotlinSpacingRules.kt @@ -70,7 +70,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing inPosition(left = ENUM_ENTRY, right = ENUM_ENTRY).emptyLinesIfLineBreakInLeft( emptyLines = 0, numberOfLineFeedsOtherwise = 0, numSpacesOtherwise = 1) - inPosition(parent = CLASS_BODY, left = SEMICOLON).customRule { parent, left, right -> + inPosition(parent = CLASS_BODY, left = SEMICOLON).customRule { parent, _, right -> val klass = parent.node.treeParent.psi as? KtClass ?: return@customRule null if (klass.isEnum() && right.node.elementType in DECLARATIONS) { createSpacing(0, minLineFeeds = 2, keepBlankLines = settings.KEEP_BLANK_LINES_IN_DECLARATIONS) @@ -78,7 +78,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing } val parameterWithDocCommentRule = { - parent: ASTBlock, left: ASTBlock, right: ASTBlock -> + _: ASTBlock, _: ASTBlock, right: ASTBlock -> if (right.node.firstChildNode.elementType == KtTokens.DOC_COMMENT) { createSpacing(0, minLineFeeds = 1, keepLineBreaks = true, keepBlankLines = settings.KEEP_BLANK_LINES_IN_DECLARATIONS) } @@ -184,7 +184,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing // class A() - no space before LPAR of PRIMARY_CONSTRUCTOR // class A private() - one space before modifier custom { - inPosition(right = PRIMARY_CONSTRUCTOR).customRule { p, l, r -> + inPosition(right = PRIMARY_CONSTRUCTOR).customRule { _, _, r -> val spacesCount = if (r.node.findLeafElementAt(0)?.elementType != LPAR) 1 else 0 createSpacing(spacesCount, minLineFeeds = 0, keepLineBreaks = true, keepBlankLines = 0) } @@ -264,14 +264,14 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing shouldBeOnNewLine: Boolean, keyword: IElementType, parent: IElementType, - afterBlockFilter: (wordParent: ASTNode, block: ASTNode) -> Boolean = { keywordParent, block -> true }) { + afterBlockFilter: (wordParent: ASTNode, block: ASTNode) -> Boolean = { _, _ -> true }) { if (shouldBeOnNewLine) { inPosition(parent = parent, right = keyword) .lineBreakIfLineBreakInParent(numSpacesOtherwise = 1, allowBlankLines = false) } else { inPosition(parent = parent, right = keyword).customRule { - parent, left, right -> + _, _, right -> val previousLeaf = builderUtil.getPreviousNonWhitespaceLeaf(right.node) val leftBlock = if ( @@ -312,17 +312,17 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing } fun leftBraceRule(blockType: IElementType = BLOCK) = { - parent: ASTBlock, left: ASTBlock, right: ASTBlock -> + _: ASTBlock, _: ASTBlock, right: ASTBlock -> spacingForLeftBrace(right.node, blockType) } val leftBraceRuleIfBlockIsWrapped = { - parent: ASTBlock, left: ASTBlock, right: ASTBlock -> + _: ASTBlock, _: ASTBlock, right: ASTBlock -> spacingForLeftBrace(right.node!!.firstChildNode) } if (kotlinCommonSettings.KEEP_FIRST_COLUMN_COMMENT) { - inPosition(parent = null, left = EOL_COMMENT, right = EOL_COMMENT).customRule { parent, left, right -> + inPosition(parent = null, left = EOL_COMMENT, right = EOL_COMMENT).customRule { _, _, right -> val nodeBeforeRight = right.node.treePrev if (nodeBeforeRight is PsiWhiteSpace && !nodeBeforeRight.textContains('\n')) { // Several line comments happened to be generated in one line @@ -338,7 +338,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing } // Add space after a semicolon if there is another child at the same line - inPosition(left = SEMICOLON).customRule { parent, left, right -> + inPosition(left = SEMICOLON).customRule { _, left, _ -> val nodeAfterLeft = left.node.treeNext if (nodeAfterLeft is PsiWhiteSpace && !nodeAfterLeft.textContains('\n')) { createSpacing(1) @@ -368,7 +368,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing inPosition(parent = WHEN_ENTRY, right = BLOCK).customRule(leftBraceRule()) inPosition(parent = WHEN, right = LBRACE).customRule { - parent, left, right -> + parent, _, _ -> spacingForLeftBrace(block = parent.node, blockType = WHEN) } @@ -395,7 +395,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing inPosition(parent = FUNCTION_LITERAL, left = LBRACE) .customRule { - parent, left, right -> + _, _, right -> val rightNode = right.node!! val rightType = rightNode.elementType var numSpaces = spacesInSimpleFunction @@ -412,7 +412,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing inPosition(parent = CLASS_BODY, right = RBRACE).lineBreakIfLineBreakInParent(numSpacesOtherwise = 1) - inPosition(parent = BLOCK, right = RBRACE).customRule { block, left, right -> + inPosition(parent = BLOCK, right = RBRACE).customRule { block, left, _ -> val psiElement = block.node.treeParent.psi val empty = left.node.elementType == LBRACE @@ -433,7 +433,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing commonCodeStyleSettings.KEEP_BLANK_LINES_IN_CODE) } - inPosition(parent = BLOCK, left = LBRACE).customRule { parent, left, right -> + inPosition(parent = BLOCK, left = LBRACE).customRule { parent, _, _ -> val psiElement = parent.node.treeParent.psi val funNode = psiElement as? KtFunction ?: return@customRule null diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt index c7f7aec42dc..d5548e6a4be 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt @@ -43,7 +43,6 @@ import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.expressions.DoubleColonLHS import org.jetbrains.kotlin.types.typeUtil.isUnit -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* class ReferenceVariantsHelper( @@ -281,7 +280,7 @@ class ReferenceVariantsHelper( val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList() val staticDescriptors = qualifier.staticScope.getDescriptorsFiltered(kindFilter, nameFilter) - val objectDescriptor = (qualifier as? ClassQualifier)?.descriptor?.check { it.kind == ClassKind.OBJECT } ?: return staticDescriptors + val objectDescriptor = (qualifier as? ClassQualifier)?.descriptor?.takeIf { it.kind == ClassKind.OBJECT } ?: return staticDescriptors return staticDescriptors + objectDescriptor.defaultType.memberScope.getDescriptorsFiltered(kindFilter, nameFilter) } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt index fafcc9b7bf1..1fef5aeb914 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt @@ -41,7 +41,6 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.expressions.DoubleColonLHS import org.jetbrains.kotlin.util.supertypesWithAny import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.lang.RuntimeException import java.util.* @@ -261,7 +260,7 @@ fun CallTypeAndReceiver<*, *>.receiverTypesWithIndex( is CallTypeAndReceiver.SUPER_MEMBERS -> { val qualifier = receiver.superTypeQualifier if (qualifier != null) { - return bindingContext.getType(receiver).singletonOrEmptyList().map { ReceiverType(it, 0) } + return listOfNotNull(bindingContext.getType(receiver)).map { ReceiverType(it, 0) } } else { val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade) diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt index 2ed72813077..3f0fec21839 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt @@ -27,7 +27,6 @@ import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.Constrain import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.checker.StrictEqualityTypeChecker import org.jetbrains.kotlin.types.typeUtil.* -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* fun CallableDescriptor.fuzzyReturnType() = returnType?.toFuzzyType(typeParameters) @@ -182,7 +181,7 @@ class FuzzyType( valueTransform = { val typeProjection = TypeProjectionImpl(Variance.INVARIANT, it.defaultType) val substitutedProjection = substitutorToKeepCapturedTypes.substitute(typeProjection) - substitutedProjection?.check { !ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection + substitutedProjection?.takeIf { !ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection }) return TypeConstructorSubstitution.createByConstructorsMap(substitutionMap, approximateCapturedTypes = true).buildSubstitutor() } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt index ea159d5b709..78e5355feb0 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt @@ -39,7 +39,6 @@ import org.jetbrains.kotlin.resolve.scopes.ImportingScope import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.parentsWithSelf import org.jetbrains.kotlin.resolve.scopes.utils.replaceImportingScopes -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.util.* class OptimizedImportsBuilder( @@ -294,7 +293,7 @@ class OptimizedImportsBuilder( names.flatMap { name -> scope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) + scope.getContributedVariables(name, NoLookupLocation.FROM_IDE) + - scope.getContributedClassifier(name, NoLookupLocation.FROM_IDE).singletonOrEmptyList() + listOfNotNull(scope.getContributedClassifier(name, NoLookupLocation.FROM_IDE)) } } .filter { it.isNotEmpty() } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt index f24fe59ebba..6847aebad4f 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt @@ -33,7 +33,6 @@ import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.* import org.jetbrains.kotlin.utils.SmartSet -import org.jetbrains.kotlin.utils.addToStdlib.singletonList fun KotlinType.approximateFlexibleTypes( preferNotNull: Boolean = false, @@ -118,7 +117,7 @@ fun KotlinType.anonymousObjectSuperTypeOrNull(): KotlinType? { } fun KotlinType.getResolvableApproximations(scope: LexicalScope?, checkTypeParameters: Boolean): Sequence { - return (singletonList() + TypeUtils.getAllSupertypes(this)) + return (listOf(this) + TypeUtils.getAllSupertypes(this)) .asSequence() .filter { it.isResolvableInScope(scope, checkTypeParameters) } .mapNotNull mapArgs@ { diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt index 60dfdfa6c15..ba37f70c866 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt @@ -679,7 +679,7 @@ class KotlinPsiUnifier( decl2: KtDeclaration, desc1: DeclarationDescriptor?, desc2: DeclarationDescriptor?): Status? { - if (decl1.javaClass != decl2.javaClass) return UNMATCHED + if (decl1::class.java != decl2::class.java) return UNMATCHED if (desc1 == null || desc2 == null) { if (decl1 is KtParameter @@ -689,7 +689,7 @@ class KotlinPsiUnifier( return UNMATCHED } if (ErrorUtils.isError(desc1) || ErrorUtils.isError(desc2)) return UNMATCHED - if (desc1.javaClass != desc2.javaClass) return UNMATCHED + if (desc1::class.java != desc2::class.java) return UNMATCHED declarationPatternsToTargets.putValue(desc1, desc2) val status = when (decl1) { diff --git a/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt b/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt index f4e67e17bd1..a93bbb9af67 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt @@ -39,6 +39,6 @@ class ExplicitImportsScope(private val descriptors: Collection { val library = orderEntry.library ?: return listOf() - emptyOrSingletonList(LibraryInfo(project, library)) + listOfNotNull(LibraryInfo(project, library)) } is JdkOrderEntry -> { val sdk = orderEntry.jdk ?: return listOf() - emptyOrSingletonList(SdkInfo(project, sdk)) + listOfNotNull(SdkInfo(project, sdk)) } else -> { throw IllegalStateException("Unexpected order entry $orderEntry") diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KotlinCacheServiceImpl.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KotlinCacheServiceImpl.kt index 0a279f1ff90..b90a20013ee 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KotlinCacheServiceImpl.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/KotlinCacheServiceImpl.kt @@ -262,7 +262,7 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService { ) } - else -> throw IllegalStateException("Unknown IdeaModuleInfo ${syntheticFileModule.javaClass}") + else -> throw IllegalStateException("Unknown IdeaModuleInfo ${syntheticFileModule::class.java}") } } @@ -351,7 +351,7 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService { private fun KtCodeFragment.getContextFile(): KtFile? { val contextElement = context ?: return null val contextFile = (contextElement as? KtElement)?.containingKtFile - ?: throw AssertionError("Analyzing kotlin code fragment of type $javaClass with java context of type ${contextElement.javaClass}") + ?: throw AssertionError("Analyzing kotlin code fragment of type ${this::class.java} with java context of type ${contextElement::class.java}") return if (contextFile is KtCodeFragment) contextFile.getContextFile() else contextFile } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/MapPsiToAsmDesc.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/MapPsiToAsmDesc.kt index 993758aa39d..a12276158a2 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/MapPsiToAsmDesc.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/MapPsiToAsmDesc.kt @@ -44,11 +44,11 @@ object MapPsiToAsmDesc { is PsiTypeParameter -> resolved.superTypes.firstOrNull()?.let { typeDesc(it) } ?: "Ljava/lang/Object;" is PsiClass -> classDesc(resolved) null -> unknownSignature() - else -> error("Resolved to unexpected $resolved of class ${resolved.javaClass}" ) + else -> error("Resolved to unexpected $resolved of class ${resolved::class.java}" ) } } - else -> error("Unexpected type $type of class ${type.javaClass}") + else -> error("Unexpected type $type of class ${type::class.java}") } private fun classDesc(psiClass: PsiClass) = buildString { @@ -81,5 +81,5 @@ object MapPsiToAsmDesc { } private fun primitive(asmType: Type) = asmType.descriptor - private val LOG = Logger.getInstance(javaClass) + private val LOG = Logger.getInstance(this::class.java) } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ScriptModuleInfos.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ScriptModuleInfos.kt index e16ec1b1713..ade224dd8ee 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ScriptModuleInfos.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ScriptModuleInfos.kt @@ -29,7 +29,6 @@ import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.script.KotlinScriptDefinition import org.jetbrains.kotlin.script.KotlinScriptExternalDependencies import org.jetbrains.kotlin.script.KotlinScriptExternalImportsProvider -import org.jetbrains.kotlin.utils.singletonOrEmptyList class ScriptModuleSearchScope(val scriptFile: VirtualFile, baseScope: GlobalSearchScope) : DelegatingGlobalSearchScope(baseScope) { override fun equals(other: Any?) = other is ScriptModuleSearchScope && scriptFile == other.scriptFile && super.equals(other) @@ -59,7 +58,7 @@ data class ScriptModuleInfo(val project: Project, val scriptFile: VirtualFile, } private fun sdkDependencies(scriptDependencies: KotlinScriptExternalDependencies?, project: Project): List - = findJdk(scriptDependencies, project)?.let { SdkInfo(project, it) }.singletonOrEmptyList() + = listOfNotNull(findJdk(scriptDependencies, project)?.let { SdkInfo(project, it) }) fun findJdk(dependencies: KotlinScriptExternalDependencies?, project: Project): Sdk? { val allJdks = getAllProjectSdks() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/getModuleInfo.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/getModuleInfo.kt index 9cbff6eada6..e19c8e6d386 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/getModuleInfo.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/getModuleInfo.kt @@ -56,7 +56,7 @@ private fun PsiElement.getModuleInfo(onFailure: (String) -> IdeaModuleInfo?): Id val doNotAnalyze = containingJetFile?.doNotAnalyze if (doNotAnalyze != null) { return onFailure( - "Should not analyze element: $text in file ${containingJetFile?.name ?: " "}\n$doNotAnalyze" + "Should not analyze element: $text in file ${containingJetFile.name}\n$doNotAnalyze" ) } @@ -65,13 +65,13 @@ private fun PsiElement.getModuleInfo(onFailure: (String) -> IdeaModuleInfo?): Id if (containingJetFile is KtCodeFragment) { return containingJetFile.getContext()?.getModuleInfo() - ?: onFailure("Analyzing code fragment of type ${containingJetFile.javaClass} with no context element\nText:\n${containingJetFile.getText()}") + ?: onFailure("Analyzing code fragment of type ${containingJetFile::class.java} with no context element\nText:\n${containingJetFile.getText()}") } - val containingFile = containingFile ?: return onFailure("Analyzing element of type $javaClass with no containing file\nText:\n$text") + val containingFile = containingFile ?: return onFailure("Analyzing element of type ${this::class.java} with no containing file\nText:\n$text") val virtualFile = containingFile.originalFile.virtualFile - ?: return onFailure("Analyzing element of type $javaClass in non-physical file $containingFile of type ${containingFile.javaClass}\nText:\n$text") + ?: return onFailure("Analyzing element of type ${this::class.java} in non-physical file $containingFile of type ${containingFile::class.java}\nText:\n$text") return getModuleInfoByVirtualFile( project, diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt index 5008520540e..edd288950d3 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt @@ -146,7 +146,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { val typeProjection = KotlinTypeProjectionStubImpl(typeArgumentsListStub, projectionKind.ordinal) if (projectionKind != KtProjectionKind.STAR) { val modifierKeywordToken = projectionKind.token as? KtModifierKeywordToken - createModifierListStub(typeProjection, modifierKeywordToken.singletonOrEmptyList()) + createModifierListStub(typeProjection, listOfNotNull(modifierKeywordToken)) createTypeReferenceStub(typeProjection, typeArgumentProto.type(c.typeTable)!!) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt index baa8b735585..e3aa7ba3c07 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt @@ -142,7 +142,7 @@ fun createStubForPackageName(packageDirectiveStub: KotlinPlaceHolderStubImpl, - bindTypeArguments: (KotlinUserTypeStub, Int) -> Unit = { x, y -> } + bindTypeArguments: (KotlinUserTypeStub, Int) -> Unit = { _, _ -> } ): KotlinUserTypeStub { val substituteWithAny = typeClassId.isLocal diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinPsiChecker.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinPsiChecker.kt index f94c77965b9..c74e4f26b8d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinPsiChecker.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinPsiChecker.kt @@ -49,7 +49,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.lang.reflect.* import java.util.* @@ -102,7 +101,7 @@ open class KotlinPsiChecker : Annotator, HighlightRangeExtension { ) fun createQuickFixes(diagnostic: Diagnostic): Collection = - createQuickFixes(diagnostic.singletonOrEmptyList())[diagnostic] + createQuickFixes(listOfNotNull(diagnostic))[diagnostic] private val UNRESOLVED_KEY = Key("KotlinPsiChecker.UNRESOLVED_KEY") @@ -133,7 +132,7 @@ private fun createQuickFixes(similarDiagnostics: Collection): MultiM actions.putValues(diagnostic, QuickFixes.getInstance().getActions(diagnostic.factory)) } - actions.values().forEach { NoDeclarationDescriptorsChecker.check(it.javaClass) } + actions.values().forEach { NoDeclarationDescriptorsChecker.check(it::class.java) } return actions } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt index ae629629023..a06d686769d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt @@ -57,13 +57,13 @@ abstract class IntentionBasedInspection( intention: KClass>, additionalChecker: (TElement) -> Boolean, problemText: String? = null - ) : this(listOf(IntentionData(intention, { element, inspection -> additionalChecker(element) } )), problemText) + ) : this(listOf(IntentionData(intention, { element, _ -> additionalChecker(element) } )), problemText) data class IntentionData( val intention: KClass>, - val additionalChecker: (TElement, IntentionBasedInspection) -> Boolean = { element, inspection -> true } + val additionalChecker: (TElement, IntentionBasedInspection) -> Boolean = { _, _ -> true } ) open fun additionalFixes(element: TElement): List? = null diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt index a51d4a9ed9f..95086e8bd9d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt @@ -217,7 +217,7 @@ class OperatorToFunctionIntention : SelfTargetingIntention(KtExpre callExpression.valueArgumentList?.delete() } } - return callee.parent!!.replace(transformed) as KtExpression + return callee.parent.replace(transformed) as KtExpression } fun convert(element: KtExpression): Pair { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt index d4d51a189b6..229cca7352e 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt @@ -101,14 +101,14 @@ abstract class SelfTargetingIntention( internal set protected fun isIntentionBaseInspectionEnabled(project: Project, target: TElement): Boolean { - val inspection = inspection ?: findInspection(this.javaClass.kotlin) ?: return false + val inspection = inspection ?: findInspection(this::class.java.kotlin) ?: return false val key = HighlightDisplayKey.find(inspection.shortName) if (!InspectionProjectProfileManager.getInstance(project).inspectionProfile.isToolEnabled(key, target)) { return false } - return inspection.intentionInfos.single { it.intention == this.javaClass.kotlin }.additionalChecker(target, inspection) + return inspection.intentionInfos.single { it.intention == this::class.java.kotlin }.additionalChecker(target, inspection) } final override fun invoke(project: Project, editor: Editor, file: PsiFile): Unit { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt index e7baf3f8ffc..2ce59735b22 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.psi.KtCodeFragment -import org.jetbrains.kotlin.utils.singletonOrEmptyList abstract class KotlinIntentionActionsFactory { protected open fun isApplicableForCodeFragment(): Boolean = false @@ -30,7 +29,7 @@ abstract class KotlinIntentionActionsFactory { sameTypeDiagnostics: Collection): List = emptyList() fun createActions(diagnostic: Diagnostic): List = - createActions(diagnostic.singletonOrEmptyList(), false) + createActions(listOfNotNull(diagnostic), false) fun createActionsForAllProblems(sameTypeDiagnostics: Collection): List = createActions(sameTypeDiagnostics, true) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt index c5cc560db0c..88d6cb2a158 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt @@ -26,11 +26,10 @@ import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtDestructuringDeclaration import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.utils.singletonOrEmptyList class KtDestructuringDeclarationReference(element: KtDestructuringDeclarationEntry) : AbstractKtReference(element) { override fun getTargetDescriptors(context: BindingContext): Collection { - return context[BindingContext.COMPONENT_RESOLVED_CALL, element]?.candidateDescriptor.singletonOrEmptyList() + return listOfNotNull(context[BindingContext.COMPONENT_RESOLVED_CALL, element]?.candidateDescriptor) } override fun getRangeInElement() = TextRange(0, element.textLength) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtReference.kt index 01f0a57ac0a..9eea144ec58 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtReference.kt @@ -28,7 +28,6 @@ import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* interface KtReference : PsiPolyVariantReference { @@ -95,7 +94,7 @@ abstract class AbstractKtReference(element: T) if (targetDescriptor is PackageViewDescriptor) { val psiFacade = JavaPsiFacade.getInstance(expression.project) val fqName = targetDescriptor.fqName.asString() - return psiFacade.findPackage(fqName).singletonOrEmptyList() + return listOfNotNull(psiFacade.findPackage(fqName)) } else { return DescriptorToSourceUtilsIde.getAllDeclarations(expression.project, targetDescriptor) @@ -105,10 +104,7 @@ abstract class AbstractKtReference(element: T) protected abstract fun getTargetDescriptors(context: BindingContext): Collection private fun getLabelTargets(context: BindingContext): Collection? { - val reference = expression - if (reference !is KtReferenceExpression) { - return null - } + val reference = expression as? KtReferenceExpression ?: return null val labelTarget = context[BindingContext.LABEL_TARGET, reference] if (labelTarget != null) { return listOf(labelTarget) @@ -116,7 +112,7 @@ abstract class AbstractKtReference(element: T) return context[BindingContext.AMBIGUOUS_LABEL_TARGET, reference] } - override fun toString() = javaClass.simpleName + ": " + expression.text + override fun toString() = this::class.java.simpleName + ": " + expression.text } abstract class KtSimpleReference(expression: T) : AbstractKtReference(expression) { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt index 64e9eb91c44..00e3aae75e8 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt @@ -39,7 +39,6 @@ import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.utils.addToStdlib.constant import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull -import org.jetbrains.kotlin.utils.emptyOrSingletonList import java.util.* // Navigation element of the resolved reference @@ -56,7 +55,7 @@ val PsiReference.unwrappedTargets: Set return when (this) { is PsiPolyVariantReference -> multiResolve(false).mapNotNullTo(HashSet()) { it.element?.adjust() } - else -> emptyOrSingletonList(resolve()?.adjust()).toSet() + else -> listOfNotNull(resolve()?.adjust()).toSet() } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/OperatorReferenceSearcher.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/OperatorReferenceSearcher.kt index bb0000bd5ad..ccf03823294 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/OperatorReferenceSearcher.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/OperatorReferenceSearcher.kt @@ -48,7 +48,6 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.isValidOperator -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* abstract class OperatorReferenceSearcher( @@ -227,7 +226,7 @@ abstract class OperatorReferenceSearcher( } private fun extractReceiverType(): FuzzyType? { - val descriptor = resolveTargetToDescriptor()?.check { it.isValidOperator() } ?: return null + val descriptor = resolveTargetToDescriptor()?.takeIf { it.isValidOperator() } ?: return null return if (descriptor.isExtension) { descriptor.fuzzyExtensionReceiverType()!! diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/utils.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/utils.kt index 686bec219b0..d8e04c8a1bf 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/utils.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/utils.kt @@ -41,7 +41,6 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.OverridingUtil -import org.jetbrains.kotlin.utils.addToStdlib.check val KtDeclaration.descriptor: DeclarationDescriptor? get() = this.analyze().get(BindingContext.DECLARATION_TO_DESCRIPTOR, this) @@ -163,7 +162,7 @@ private fun processInheritorsDelegatingCallToSpecifiedConstructor( ): Boolean { return HierarchySearchRequest(klass, scope, false).searchInheritors().all { runReadAction { - val unwrapped = it.check { it.isValid }?.unwrapped + val unwrapped = it.takeIf { it.isValid }?.unwrapped if (unwrapped is KtClass) processClassDelegationCallsToSpecifiedConstructor(unwrapped, descriptor, process) else diff --git a/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt b/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt index 3fe1c58d286..1e50b587fef 100644 --- a/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt +++ b/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt @@ -90,7 +90,7 @@ private fun String.amendNextLinesIfNeeded(reader: OutputLineReader): String { if (nextLine != null) { // This code is needed for compatibility with AS 2.0 and IDEA 15.0, because of difference in android plugins val positionField = try { - reader.javaClass.getDeclaredField("myPosition") + reader::class.java.getDeclaredField("myPosition") } catch(e: Throwable) { null diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/actions/NewKotlinActivityAction.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/actions/NewKotlinActivityAction.kt index 2771d504936..914800ec0f8 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/actions/NewKotlinActivityAction.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/actions/NewKotlinActivityAction.kt @@ -34,8 +34,8 @@ import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.actions.JavaToKotlinAction import org.jetbrains.kotlin.idea.refactoring.toPsiFile import java.io.File -import kotlin.reflect.functions -import kotlin.reflect.memberFunctions +import kotlin.reflect.full.functions +import kotlin.reflect.full.memberFunctions private val NEW_KOTLIN_ACTIVITY_START_LABEL = "Start New Kotlin Activity Action" private val NEW_KOTLIN_ACTIVITY_END_LABEL = "Finish New Kotlin Activity Action" diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt index 4ec4f33c9cd..f348626327f 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt @@ -51,7 +51,6 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.util.supertypesWithAny -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* @@ -347,8 +346,8 @@ class BasicCompletionSession( if (userType != typeRef.typeElement) return null val parent = typeRef.parent return when (parent) { - is KtNamedFunction -> parent.check { typeRef == it.receiverTypeReference } - is KtProperty -> parent.check { typeRef == it.receiverTypeReference } + is KtNamedFunction -> parent.takeIf { typeRef == it.receiverTypeReference } + is KtProperty -> parent.takeIf { typeRef == it.receiverTypeReference } else -> null } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionUtils.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionUtils.kt index bab90fee2cf..bbd1a0afec4 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionUtils.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionUtils.kt @@ -46,7 +46,6 @@ import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.kotlin.types.typeUtil.nullability -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* tailrec fun LookupElement.putUserDataDeep(key: Key, value: T?) { @@ -413,7 +412,7 @@ fun ImportableFqNameClassifier.isImportableDescriptorImported(descriptor: Declar fun OffsetMap.tryGetOffset(key: OffsetKey): Int? { try { - return getOffset(key).check { it != -1 } // prior to IDEA 2016.3 getOffset() returned -1 if not found, now it throws exception + return getOffset(key).takeIf { it != -1 } // prior to IDEA 2016.3 getOffset() returned -1 if not found, now it throws exception } catch(e: Exception) { return null diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt index 5130f5bab14..df083acd1a3 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt @@ -56,7 +56,7 @@ abstract class DeclarationLookupObjectImpl( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other == null || javaClass != other.javaClass) return false + if (other == null || this::class.java != other::class.java) return false val lookupObject = other as DeclarationLookupObjectImpl if (descriptor != null) return descriptorsEqualWithSubstitution(descriptor, lookupObject.descriptor) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt index f9c8484924c..a31a6bb9dda 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt @@ -34,7 +34,6 @@ import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* class StaticMembersCompletion( @@ -52,11 +51,11 @@ class StaticMembersCompletion( return object : AbstractLookupElementFactory { override fun createStandardLookupElementsForDescriptor(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean): Collection { if (!useReceiverTypes) return emptyList() - return lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false) - .decorateAsStaticMember(descriptor, classNameAsLookupString = false) - ?.assignPriority(itemPriority) - ?.suppressAutoInsertion() - .singletonOrEmptyList() + return listOfNotNull(lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false) + .decorateAsStaticMember(descriptor, classNameAsLookupString = false) + ?.assignPriority(itemPriority) + ?.suppressAutoInsertion() + ) } override fun createLookupElement(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean, diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt index 3385f2c7b9b..e6fab485e7a 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt @@ -75,12 +75,12 @@ class ToFromOriginalFileMapper private constructor( fun toOriginalFile(element: TElement): TElement? { if (element.containingFile != syntheticFile) return element val offset = toOriginalFile(element.startOffset) ?: return null - return PsiTreeUtil.findElementOfClassAtOffset(originalFile, offset, element.javaClass, true) + return PsiTreeUtil.findElementOfClassAtOffset(originalFile, offset, element::class.java, true) } fun toSyntheticFile(element: TElement): TElement? { if (element.containingFile != originalFile) return element val offset = toSyntheticFile(element.startOffset) ?: return null - return PsiTreeUtil.findElementOfClassAtOffset(syntheticFile, offset, element.javaClass, true) + return PsiTreeUtil.findElementOfClassAtOffset(syntheticFile, offset, element::class.java, true) } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/handlerUtils.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/handlerUtils.kt index b01b0f5814b..653b857668b 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/handlerUtils.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/handlerUtils.kt @@ -136,7 +136,7 @@ fun createKeywordConstructLookupElement( return LookupElementBuilder.create(KeywordLookupObject(), keyword) .bold() .withTailText(tailText) - .withInsertHandler { insertionContext, lookupElement -> + .withInsertHandler { insertionContext, _ -> if (insertionContext.completionChar == Lookup.NORMAL_SELECT_CHAR || insertionContext.completionChar == Lookup.REPLACE_SELECT_CHAR) { val offset = insertionContext.tailOffset val newIndent = detectIndent(insertionContext.document.charsSequence, offset - keyword.length) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt index 7c4bc39d8e7..e518a9b9952 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt @@ -58,7 +58,7 @@ object LambdaItems { for (functionType in distinctTypes) { val lookupString = lambdaPresentation(functionType) val lookupElement = LookupElementBuilder.create(lookupString) - .withInsertHandler({ context, lookupElement -> + .withInsertHandler({ context, _ -> val offset = context.startOffset val placeholder = "{}" context.document.replaceString(offset, context.tailOffset, placeholder) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt index 3012f3ad669..e58071da1f0 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt @@ -89,7 +89,7 @@ class MultipleArgumentsItemProvider( return LookupElementBuilder .create(variables.map { it.name.render() }.joinToString(", ")) //TODO: use code formatting settings - .withInsertHandler { context, lookupElement -> + .withInsertHandler { context, _ -> if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) { val offset = context.offsetMap.tryGetOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET) if (offset != null) { diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt index 41fcf7df747..85a82188f10 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt @@ -45,8 +45,6 @@ import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean import org.jetbrains.kotlin.types.typeUtil.makeNotNullable import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.check -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptySet import java.util.* @@ -94,7 +92,7 @@ class SmartCompletion( val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection)? = { descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory -> filterDescriptor(descriptor, factory).map { postProcess(it) } - }.check { expectedInfos.isNotEmpty() } + }.takeIf { expectedInfos.isNotEmpty() } fun additionalItems(lookupElementFactory: LookupElementFactory): Pair, InheritanceItemsSearcher?> { val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory) @@ -287,7 +285,7 @@ class SmartCompletion( val types = smartCastCalculator.types(item.receiverParameter).map { it.toFuzzyType(emptyList()) } val matcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) } addLookupElements(null, expectedInfos, matcher) { - item.createLookupElement().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS).singletonList() + listOf(item.createLookupElement().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS)) } } } @@ -328,7 +326,7 @@ class SmartCompletion( private fun createNamedArgumentWithValueLookupElement(name: Name, value: String, priority: SmartCompletionItemPriority): LookupElement { val lookupElement = LookupElementBuilder.create("${name.asString()} = $value") .withIcon(KotlinIcons.PARAMETER) - .withInsertHandler({ context, item -> context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value") }) + .withInsertHandler({ context, _ -> context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value") }) lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) lookupElement.assignSmartCompletionPriority(priority) return lookupElement diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt index 3e191b9f85f..8e8713a93bb 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt @@ -188,7 +188,7 @@ class TypeInstantiationItems( itemText = "object: $itemText{...}" lookupString = "object" allLookupStrings = setOf(lookupString, lookupElement.lookupString) - insertHandler = InsertHandler { context, item -> + insertHandler = InsertHandler { context, _ -> val startOffset = context.startOffset val text1 = "object: $typeText" diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt index 27462c150c5..7aef2194700 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt @@ -42,7 +42,6 @@ import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isNullableNothing import org.jetbrains.kotlin.util.descriptorsEqualWithSubstitution -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* class ArtificialElementInsertHandler( @@ -299,7 +298,7 @@ fun DeclarationDescriptor.fuzzyTypesForSmartCompletion( ): Collection { if (callTypeAndReceiver is CallTypeAndReceiver.CALLABLE_REFERENCE) { val lhs = callTypeAndReceiver.receiver?.let { bindingContext[BindingContext.DOUBLE_COLON_LHS, it] } - return (this as? CallableDescriptor)?.callableReferenceType(resolutionFacade, lhs).singletonOrEmptyList() + return listOfNotNull((this as? CallableDescriptor)?.callableReferenceType(resolutionFacade, lhs)) } if (this is CallableDescriptor) { diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt index 160bc93abb7..a49592dfd31 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt @@ -65,10 +65,10 @@ abstract class AbstractCompletionHandlerTest(private val defaultCompletionType: val settingName = line.substring(0, index).trim() val settingValue = line.substring(index + 1).trim() val (field, settings) = try { - kotlinStyleSettings.javaClass.getDeclaredField(settingName) to kotlinStyleSettings + kotlinStyleSettings::class.java.getDeclaredField(settingName) to kotlinStyleSettings } catch (e: NoSuchFieldException) { - commonStyleSettings.javaClass.getDeclaredField(settingName) to commonStyleSettings + commonStyleSettings::class.java.getDeclaredField(settingName) to commonStyleSettings } when (field.type.name) { "boolean" -> field.setBoolean(settings, settingValue.toBoolean()) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt index 2fdee33f184..9956766bb98 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt @@ -40,8 +40,6 @@ import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.* -import org.jetbrains.kotlin.utils.addToStdlib.check -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* enum class Tail { @@ -66,7 +64,7 @@ interface ByTypeFilter { get() = null val multipleFuzzyTypes: Collection - get() = fuzzyType.singletonOrEmptyList() + get() = listOfNotNull(fuzzyType) object All : ByTypeFilter { override fun matchingSubstitutor(descriptorType: FuzzyType) = TypeSubstitutor.EMPTY @@ -543,13 +541,13 @@ class ExpectedInfos( val declaration = expressionWithType.parent as? KtDeclarationWithBody ?: return null if (expressionWithType != declaration.bodyExpression || declaration.hasBlockBody()) return null val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] as? FunctionDescriptor ?: return null - return functionReturnValueExpectedInfo(descriptor, hasExplicitReturnType = declaration.hasDeclaredReturnType()).singletonOrEmptyList() + return listOfNotNull(functionReturnValueExpectedInfo(descriptor, hasExplicitReturnType = declaration.hasDeclaredReturnType())) } private fun calculateForReturn(expressionWithType: KtExpression): Collection? { val returnExpression = expressionWithType.parent as? KtReturnExpression ?: return null val descriptor = returnExpression.getTargetFunctionDescriptor(bindingContext) ?: return null - return functionReturnValueExpectedInfo(descriptor, hasExplicitReturnType = true).singletonOrEmptyList() + return listOfNotNull(functionReturnValueExpectedInfo(descriptor, hasExplicitReturnType = true)) } private fun functionReturnValueExpectedInfo(descriptor: FunctionDescriptor, hasExplicitReturnType: Boolean): ExpectedInfo? { @@ -582,7 +580,7 @@ class ExpectedInfos( val loopVar = forExpression.loopParameter val loopVarType = if (loopVar != null && loopVar.typeReference != null) - (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, loopVar] as VariableDescriptor).type.check { !it.isError } + (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, loopVar] as VariableDescriptor).type.takeIf { !it.isError } else null @@ -624,7 +622,7 @@ class ExpectedInfos( ?: property.dispatchReceiverParameter?.type?.toFuzzyType(emptyList()) ?: property.builtIns.nullableNothingType.toFuzzyType(emptyList()) - val explicitPropertyType = property.fuzzyReturnType()?.check { propertyDeclaration.typeReference != null } + val explicitPropertyType = property.fuzzyReturnType()?.takeIf { propertyDeclaration.typeReference != null } ?: property.overriddenDescriptors.singleOrNull()?.fuzzyReturnType() // for override properties use super property type as explicit (if not specified) val typesWithGetDetector = TypesWithGetValueDetector(scope, indicesHelper, propertyOwnerType, explicitPropertyType) val typesWithSetDetector = if (property.isVar) TypesWithSetValueDetector(scope, indicesHelper, propertyOwnerType) else null diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt index 8abafbc14fc..fbeb3fd4a2d 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt @@ -47,7 +47,6 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.isHiddenInResolution import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.lang.reflect.Field import java.lang.reflect.Modifier import java.util.* @@ -270,7 +269,7 @@ class KotlinIndicesHelper( val shortNamesCache = PsiShortNamesCache.getInstance(project) if (shortNamesCache is CompositeShortNamesCache) { try { - fun getMyCachesField(clazz: Class): Field { + fun getMyCachesField(clazz: Class): Field { try { return clazz.getDeclaredField("myCaches") } @@ -283,16 +282,16 @@ class KotlinIndicesHelper( } } - val myCachesField = getMyCachesField(shortNamesCache.javaClass) + val myCachesField = getMyCachesField(shortNamesCache::class.java) val previousIsAccessible = myCachesField.isAccessible try { myCachesField.isAccessible = true @Suppress("UNCHECKED_CAST") return@lazy (myCachesField.get(shortNamesCache) as Array).filter { it !is KotlinShortNamesCache - && it.javaClass.name != "com.android.tools.idea.databinding.BrShortNamesCache" - && it.javaClass.name != "com.android.tools.idea.databinding.DataBindingComponentShortNamesCache" - && it.javaClass.name != "com.android.tools.idea.databinding.DataBindingShortNamesCache" + && it::class.java.name != "com.android.tools.idea.databinding.BrShortNamesCache" + && it::class.java.name != "com.android.tools.idea.databinding.DataBindingComponentShortNamesCache" + && it::class.java.name != "com.android.tools.idea.databinding.DataBindingShortNamesCache" } } finally { @@ -479,7 +478,7 @@ class KotlinIndicesHelper( val translatedDeclaration = declarationTranslator(this) ?: return emptyList() if (!psiFilter(translatedDeclaration)) return emptyList() - return (resolutionFacade.resolveToDescriptor(translatedDeclaration)).singletonOrEmptyList() + return listOfNotNull((resolutionFacade.resolveToDescriptor(translatedDeclaration))) } } } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ShortenReferences.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ShortenReferences.kt index 4ab9efe9828..d3e13b5a0f8 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ShortenReferences.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ShortenReferences.kt @@ -49,7 +49,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.findPackage import org.jetbrains.kotlin.resolve.source.getPsi -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.lang.IllegalStateException import java.util.* @@ -384,7 +383,7 @@ class ShortenReferences(val options: (KtElement) -> Options = { Options.DEFAULT scope.findPackage(name) val canShortenNow = targetByName?.asString() == target.asString() - return if (canShortenNow) AnalyzeQualifiedElementResult.ShortenNow else AnalyzeQualifiedElementResult.ImportDescriptors(target.singletonOrEmptyList()) + return if (canShortenNow) AnalyzeQualifiedElementResult.ShortenNow else AnalyzeQualifiedElementResult.ImportDescriptors(listOfNotNull(target)) } override fun shortenElement(element: KtUserType): KtElement { diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt index 0961205d85d..f3c9a000b1d 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt @@ -133,7 +133,7 @@ fun PsiElement.deleteElementAndCleanParent() { val parent = parent deleteElementWithDelimiters(this) - deleteChildlessElement(parent, this.javaClass) + deleteChildlessElement(parent, this::class.java) } // Delete element if it doesn't contain children of a given type diff --git a/idea/idea-live-templates/tests/org/jetbrains/kotlin/idea/liveTemplates/LiveTemplatesContextTest.kt b/idea/idea-live-templates/tests/org/jetbrains/kotlin/idea/liveTemplates/LiveTemplatesContextTest.kt index d2edce7de59..a64534b6821 100644 --- a/idea/idea-live-templates/tests/org/jetbrains/kotlin/idea/liveTemplates/LiveTemplatesContextTest.kt +++ b/idea/idea-live-templates/tests/org/jetbrains/kotlin/idea/liveTemplates/LiveTemplatesContextTest.kt @@ -65,7 +65,7 @@ class LiveTemplatesContextTest : KotlinLightCodeInsightFixtureTestCase() { private fun assertInContexts(vararg expectedContexts: java.lang.Class) { myFixture.configureByFile(getTestName(false) + ".kt") val allContexts = TemplateContextType.EP_NAME.extensions.filter { it is KotlinTemplateContextType } - val enabledContexts = allContexts.filter { it.isInContext(myFixture.file, myFixture.caretOffset) }.map { it.javaClass } + val enabledContexts = allContexts.filter { it.isInContext(myFixture.file, myFixture.caretOffset) }.map { it::class.java } UsefulTestCase.assertSameElements(enabledContexts, *expectedContexts) } } diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt index 117f4ca2e39..2ce4c36bdb0 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt @@ -244,7 +244,7 @@ class PomFile private constructor(val xmlFile: XmlFile, val domModel: MavenDomPr // TODO: getPhase has been added as per https://youtrack.jetbrains.com/issue/IDEA-153582 and available only in latest IDEAs return plugin.executions.filter { it.executionId == executionId }.all { execution -> - execution.javaClass.methods.filter { it.name == "getPhase" && it.parameterTypes.isEmpty() }.all { it.invoke(execution) == DefaultPhases.None } + execution::class.java.methods.filter { it.name == "getPhase" && it.parameterTypes.isEmpty() }.all { it.invoke(execution) == DefaultPhases.None } } } diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt index 6c03c44b5d7..396c33a1b07 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt @@ -105,12 +105,12 @@ class MavenPluginSourcesMoveToBuild : PsiElementBaseIntentionAction() { override fun startInWriteAction() = true override fun invoke(project: Project, editor: Editor, element: PsiElement) { - tryInvoke(project, element) { pom, dir, execution, build -> + tryInvoke(project, element) { pom, dir, execution, _ -> pom.executionSourceDirs(execution, listOf(dir)) } } - private fun tryInvoke(project: Project, element: PsiElement, block: (pom: PomFile, dir: String, execution: MavenDomPluginExecution, build: MavenDomBuild) -> Unit = { p, d, e, b -> }): Boolean { + private fun tryInvoke(project: Project, element: PsiElement, block: (pom: PomFile, dir: String, execution: MavenDomPluginExecution, build: MavenDomBuild) -> Unit = { _, _, _, _ -> }): Boolean { val file = element.containingFile if (file == null || !MavenDomUtil.isMavenFile(file) || (element !is XmlElement && element.parent !is XmlElement)) { diff --git a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt index a09ccf4b9ed..510eddcad0d 100644 --- a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt +++ b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt @@ -76,7 +76,7 @@ abstract class AbstractKotlinMavenInspectionTest : MavenImportingTestCase() { val suggestedFixes = actual.flatMap { p -> p.second.fixes?.sortedBy { it.familyName }?.map { p.second to it } ?: emptyList() } val filenamePrefix = pomFile.nameWithoutExtension + ".fixed." - val fixFiles = pomFile.parentFile.listFiles { file, name -> name.startsWith(filenamePrefix) && name.endsWith(".xml") }.sortedBy { it.name } + val fixFiles = pomFile.parentFile.listFiles { _, name -> name.startsWith(filenamePrefix) && name.endsWith(".xml") }.sortedBy { it.name } if (fixFiles.size > suggestedFixes.size) { fail("Not all fixes were suggested by the inspection: expected count: ${fixFiles.size}, actual fixes count: ${suggestedFixes.size}") diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandExecutor.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandExecutor.kt index b3021c7be0e..0d67121f3de 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandExecutor.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandExecutor.kt @@ -48,7 +48,7 @@ class CommandExecutor(private val runner: KotlinConsoleRunner) { private fun sendCommandToProcess(command: String) { val processHandler = runner.processHandler - val processInputOS = processHandler.processInput ?: return logError(javaClass, "

Broken process stream

") + val processInputOS = processHandler.processInput ?: return logError(this::class.java, "

Broken process stream

") val charset = (processHandler as? BaseOSProcessHandler)?.charset ?: Charsets.UTF_8 val xmlRes = XML_PREAMBLE + diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/ConsoleCompilerHelper.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/ConsoleCompilerHelper.kt index afc70b10a98..6de82b3c00e 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/ConsoleCompilerHelper.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/ConsoleCompilerHelper.kt @@ -40,7 +40,7 @@ class ConsoleCompilerHelper( fun compileModule() { if (ExecutionManager.getInstance(project).contentManager.removeRunContent(executor, contentDescriptor)) { CompilerManager.getInstance(project).make(module) { - aborted: Boolean, errors: Int, warnings: Int, compileContext: CompileContext -> + _: Boolean, errors: Int, _: Int, _: CompileContext -> if (!module.isDisposed) { KotlinConsoleKeeper.getInstance(project).run(module, previousCompilationFailed = errors > 0) } diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputProcessor.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputProcessor.kt index 582196395ca..6c4d46c22af 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputProcessor.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputProcessor.kt @@ -148,7 +148,7 @@ class ReplOutputProcessor( fun printInternalErrorMessage(internalErrorText: String) = WriteCommandAction.runWriteCommandAction(project) { val promptText = "Internal error occurred. Please, send report to developers.\n" printOutput(promptText, ConsoleViewContentType.ERROR_OUTPUT, ReplIcons.RUNTIME_EXCEPTION) - logError(this.javaClass, internalErrorText) + logError(this::class.java, internalErrorText) } private fun getAttributesForSeverity(start: Int, end: Int, severity: Severity): TextAttributes { diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/gutter/ConsoleIndicatorRenderer.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/gutter/ConsoleIndicatorRenderer.kt index e3189ff6841..badb59823d6 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/gutter/ConsoleIndicatorRenderer.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/gutter/ConsoleIndicatorRenderer.kt @@ -26,5 +26,5 @@ class ConsoleIndicatorRenderer(iconWithTooltip: IconWithTooltip) : GutterIconRen override fun getTooltipText() = tooltip override fun hashCode() = icon.hashCode() - override fun equals(other: Any?) = icon == (other as? ConsoleIndicatorRenderer)?.icon ?: null + override fun equals(other: Any?) = icon == (other as? ConsoleIndicatorRenderer)?.icon } \ No newline at end of file diff --git a/idea/idea-test-framework/src/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt b/idea/idea-test-framework/src/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt index cc26e8cdae2..913149f17ce 100644 --- a/idea/idea-test-framework/src/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt +++ b/idea/idea-test-framework/src/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt @@ -128,7 +128,7 @@ abstract class KotlinLightCodeInsightFixtureTestCase : KotlinLightCodeInsightFix protected fun isAllFilesPresentInTest(): Boolean = KotlinTestUtils.isAllFilesPresentTest(getTestName(false)) protected open fun fileName(): String - = KotlinTestUtils.getTestDataFileName(this.javaClass, this.name) ?: (getTestName(false) + ".kt") + = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt") protected fun performNotWriteEditorAction(actionId: String): Boolean { val dataContext = (myFixture.editor as EditorEx).dataContext diff --git a/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt b/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt index f752935555f..da9fe19668e 100644 --- a/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt +++ b/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt @@ -84,7 +84,7 @@ class KotlinGradleModelBuilder : ModelBuilderService { methodName: String, argumentsBySourceSet: MutableMap> ) { - val taskClass = compileTask.javaClass + val taskClass = compileTask::class.java val sourceSetName = try { taskClass.findGetterMethod("getSourceSetName\$kotlin_gradle_plugin")?.invoke(compileTask) as? String } catch (e : InvocationTargetException) { @@ -101,14 +101,14 @@ class KotlinGradleModelBuilder : ModelBuilderService { private fun getCoroutines(project: Project): String? { val kotlinExtension = project.extensions.findByName("kotlin") ?: return null val experimentalExtension = try { - kotlinExtension.javaClass.getMethod("getExperimental").invoke(kotlinExtension) + kotlinExtension::class.java.getMethod("getExperimental").invoke(kotlinExtension) } catch(e: NoSuchMethodException) { return null } return try { - experimentalExtension.javaClass.getMethod("getCoroutines").invoke(experimentalExtension)?.toString() + experimentalExtension::class.java.getMethod("getCoroutines").invoke(experimentalExtension)?.toString() } catch(e: NoSuchMethodException) { null diff --git a/idea/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt b/idea/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt index 74e37b31e5d..8c34aef9dde 100644 --- a/idea/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt +++ b/idea/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt @@ -44,7 +44,7 @@ object ThreadTrackerPatcherForTeamCityTesting { IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool() // Check setup was successful and patching isn't needed - val commonPoolFactoryName = ForkJoinPool.commonPool().factory.javaClass.name + val commonPoolFactoryName = ForkJoinPool.commonPool().factory::class.java.name if (commonPoolFactoryName == IdeaForkJoinWorkerThreadFactory::class.java.name) { return } diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt index 28c85a12e9c..1e66de8cc73 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt @@ -49,7 +49,6 @@ import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase() { @@ -127,7 +126,7 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< val prototypes = if (superConstructors.isNotEmpty()) { superConstructors.mapNotNull { generateConstructor(classDescriptor, propertiesToInitialize, it) } } else { - generateConstructor(classDescriptor, propertiesToInitialize, null).singletonOrEmptyList() + listOfNotNull(generateConstructor(classDescriptor, propertiesToInitialize, null)) } if (prototypes.isEmpty()) { diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckPartialBodyResolveAction.kt b/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckPartialBodyResolveAction.kt index 65bd53d8b2c..23a5051c06e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckPartialBodyResolveAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckPartialBodyResolveAction.kt @@ -127,7 +127,7 @@ class CheckPartialBodyResolveAction : AnAction() { val offset = expression.textOffset val line = document.getLineNumber(offset) val column = offset - document.getLineStartOffset(line) - val exprName = (expression as? KtNameReferenceExpression)?.getReferencedName() ?: expression.javaClass.simpleName + val exprName = (expression as? KtNameReferenceExpression)?.getReferencedName() ?: expression::class.java.simpleName builder.append("$exprName at (${line + 1}:${column + 1})") if (expression is KtReferenceExpression) { diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInliner/ClassUsageReplacementStrategy.kt b/idea/src/org/jetbrains/kotlin/idea/codeInliner/ClassUsageReplacementStrategy.kt index 6b793555903..80cadb1aaf4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInliner/ClassUsageReplacementStrategy.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInliner/ClassUsageReplacementStrategy.kt @@ -21,7 +21,6 @@ import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis -import org.jetbrains.kotlin.utils.addToStdlib.check class ClassUsageReplacementStrategy( typeReplacement: KtUserType?, @@ -31,7 +30,7 @@ class ClassUsageReplacementStrategy( private val factory = KtPsiFactory(project) - private val typeReplacement = typeReplacement?.check { it.referenceExpression != null } + private val typeReplacement = typeReplacement?.takeIf { it.referenceExpression != null } private val typeReplacementQualifierAsExpression = typeReplacement?.qualifier?.let { factory.createExpression(it.text) } private val constructorReplacementStrategy = constructorReplacement?.let(::CallableUsageReplacementStrategy) diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt b/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt index 08b0b36959e..5b490ebde66 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInliner/MutableCodeToInline.kt @@ -25,7 +25,6 @@ import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList private val POST_INSERTION_ACTION: Key<(KtElement) -> Unit> = Key("POST_INSERTION_ACTION") @@ -70,7 +69,7 @@ internal class MutableCodeToInline( } val expressions: Collection - get() = statementsBefore + mainExpression.singletonOrEmptyList() + get() = statementsBefore + listOfNotNull(mainExpression) operator fun contains(element: PsiElement): Boolean { return expressions.any { it.isAncestor(element) } diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInliner/ReplacementPerformer.kt b/idea/src/org/jetbrains/kotlin/idea/codeInliner/ReplacementPerformer.kt index c99ccc0793c..22c6b9476c2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInliner/ReplacementPerformer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInliner/ReplacementPerformer.kt @@ -26,8 +26,6 @@ import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.singletonList -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* internal abstract class ReplacementPerformer( @@ -51,7 +49,7 @@ internal class AnnotationEntryReplacementPerformer( val dummyAnnotationEntry = createByPattern("@Dummy($0)", codeToInline.mainExpression!!) { psiFactory.createAnnotationEntry(it) } val replaced = elementToBeReplaced.replace(dummyAnnotationEntry) - codeToInline.performPostInsertionActions(replaced.singletonList()) + codeToInline.performPostInsertionActions(listOf(replaced)) var range = PsiChildRange.singleElement(replaced) range = postProcessing(range) @@ -98,7 +96,7 @@ internal class ExpressionReplacementPerformer( } } - codeToInline.performPostInsertionActions(insertedStatements + replaced.singletonOrEmptyList()) + codeToInline.performPostInsertionActions(insertedStatements + listOfNotNull(replaced)) var range = if (replaced != null) { if (insertedStatements.isEmpty()) { diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInliner/introduceValue.kt b/idea/src/org/jetbrains/kotlin/idea/codeInliner/introduceValue.kt index 1e0bca8e1bf..37f3e4ae854 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInliner/introduceValue.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInliner/introduceValue.kt @@ -35,7 +35,6 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.utils.findLocalVariable import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.addToStdlib.check /** * Modifies [MutableCodeToInline] introducing a variable initialized by [value] and replacing all of [usages] with its use. @@ -93,7 +92,7 @@ internal fun MutableCodeToInline.introduceValue( val declaration = psiFactory.createDeclarationByPattern("val $0 = $1", name, value) statementsBefore.add(0, declaration) - val explicitType = valueType?.check { + val explicitType = valueType?.takeIf { variableNeedsExplicitType(value, valueType, expressionToBeReplaced, resolutionScope, bindingContext) } if (explicitType != null) { diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinCopyPasteReferenceProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinCopyPasteReferenceProcessor.kt index 5274d1668de..ecfd42d284f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinCopyPasteReferenceProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinCopyPasteReferenceProcessor.kt @@ -153,7 +153,7 @@ class KotlinCopyPasteReferenceProcessor : CopyPastePostProcessor(canGoInside = { it.javaClass as Class<*> !in IGNORE_REFERENCES_INSIDE }) { element -> + element.forEachDescendantOfType(canGoInside = { it::class.java as Class<*> !in IGNORE_REFERENCES_INSIDE }) { element -> val reference = element.mainReference ?: return@forEachDescendantOfType val descriptors = resolveReference(reference, bindingContext) diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KtPostfixTemplateProvider.kt b/idea/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KtPostfixTemplateProvider.kt index cecfb95a80c..3b4c87659ca 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KtPostfixTemplateProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KtPostfixTemplateProvider.kt @@ -168,7 +168,7 @@ private class KtExpressionPostfixTemplateSelector( override fun getExpressions(context: PsiElement, document: Document, offset: Int): List { val originalFile = context.containingFile.originalFile val textRange = context.textRange - val originalElement = findElementOfClassAtRange(originalFile, textRange.startOffset, textRange.endOffset, context.javaClass) + val originalElement = findElementOfClassAtRange(originalFile, textRange.startOffset, textRange.endOffset, context::class.java) ?: return emptyList() val expressions = originalElement.parentsWithSelf diff --git a/idea/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt b/idea/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt index 8dafb75dea8..bf1a2646cb0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt +++ b/idea/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt @@ -34,7 +34,7 @@ interface KotlinSingleNotificationManager { var isNotificationExists = false - val notifications = notificationsManager.getNotificationsOfType(notification.javaClass, project) + val notifications = notificationsManager.getNotificationsOfType(notification::class.java, project) for (oldNotification in notifications) { if (oldNotification == notification) { isNotificationExists = true diff --git a/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertTextJavaCopyPasteProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertTextJavaCopyPasteProcessor.kt index c20a78d4314..e7e1c8280dd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertTextJavaCopyPasteProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertTextJavaCopyPasteProcessor.kt @@ -44,7 +44,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getParentOfType -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.Transferable @@ -168,7 +167,7 @@ class ConvertTextJavaCopyPasteProcessor : CopyPastePostProcessor JavaToKotlinClassMap.INSTANCE.mapPlatformClass(descriptor!!).isNotEmpty() } - ?.let { (psiClass, descriptor) -> addImport(psiElementFactory.createImportStatement(psiClass)) } + classes.find { (_, descriptor) -> JavaToKotlinClassMap.INSTANCE.mapPlatformClass(descriptor!!).isNotEmpty() } + ?.let { (psiClass, _) -> addImport(psiElementFactory.createImportStatement(psiClass)) } if (reference.resolve() != null) return true - classes.singleOrNull()?.let { (psiClass, descriptor) -> + classes.singleOrNull()?.let { (psiClass, _) -> addImport(psiElementFactory.createImportStatement(psiClass), true) } @@ -147,7 +147,7 @@ class PlainTextPasteImportResolver(val dataForConversion: DataForConversion, val .map { it to it.getJavaMemberDescriptor(resolutionFacade) as? DeclarationDescriptorWithVisibility } .filter { canBeImported(it.second) } - members.singleOrNull()?.let { (psiMember, descriptor) -> + members.singleOrNull()?.let { (psiMember, _) -> addImport(psiElementFactory.createImportStaticStatement(psiMember.containingClass!!, psiMember.name!!), true) } diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt index 092b5656e3a..0a9c4cb8734 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt @@ -70,7 +70,7 @@ class KotlinEditorTextProvider : EditorTextProvider { } } - val parent = ktElement.parent ?: return null + val parent = ktElement.parent val newExpression = when (parent) { is KtThisExpression -> parent @@ -138,7 +138,7 @@ class KotlinEditorTextProvider : EditorTextProvider { arrayOf(KtUserType::class.java, KtImportDirective::class.java, KtPackageDirective::class.java, KtValueArgumentName::class.java) fun isAcceptedAsCodeFragmentContext(element: PsiElement): Boolean { - return !NOT_ACCEPTED_AS_CONTEXT_TYPES.contains(element.javaClass as Class<*>) && + return !NOT_ACCEPTED_AS_CONTEXT_TYPES.contains(element::class.java as Class<*>) && PsiTreeUtil.getParentOfType(element, *NOT_ACCEPTED_AS_CONTEXT_TYPES) == null } } diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt index 2e0f3344742..51381286e07 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt @@ -39,7 +39,6 @@ import org.jetbrains.kotlin.idea.refactoring.getLineStartOffset import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider { @@ -64,7 +63,7 @@ private fun findAdditionalExpressions(position: SourcePosition): Set 0 } ?: return emptySet() + val offset = file.getLineStartOffset(line)?.takeIf { it > 0 } ?: return emptySet() val elem = file.findElementAt(offset) val containingElement = getContainingElement(elem!!) ?: elem ?: return emptySet() @@ -101,9 +100,7 @@ private fun getContainingElement(element: PsiElement): KtElement? { val contElement = PsiTreeUtil.getParentOfType(element, KtDeclaration::class.java) ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java) if (contElement is KtProperty && contElement.isLocal) { val parent = contElement.parent - if (parent != null) { - return getContainingElement(parent) - } + return getContainingElement(parent) } if (contElement is KtDeclarationWithBody) { diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt index 52c671495f1..b974d799396 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt @@ -48,7 +48,6 @@ import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.resolve.jvm.JvmClassName import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.check import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.getOrPutNullable import org.jetbrains.org.objectweb.asm.* @@ -177,7 +176,7 @@ private fun readClassFileImpl(project: Project, } private fun findClassFileByPath(packageName: String, className: String, outputDir: VirtualFile): File? { - val outDirFile = File(outputDir.path).check(File::exists) ?: return null + val outDirFile = File(outputDir.path).takeIf(File::exists) ?: return null val parentDirectory = File(outDirFile, packageName.replace(".", File.separator)) if (!parentDirectory.exists()) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt index babfef6c640..10930a0d2a0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt @@ -233,7 +233,7 @@ class KotlinFieldBreakpoint( inline fun findRequest(debugProcess: DebugProcessImpl, requestClass: Class, requestor: Requestor): T? { val requests = debugProcess.requestsManager.findRequests(requestor) for (eventRequest in requests) { - if (eventRequest.javaClass == requestClass) { + if (eventRequest::class.java == requestClass) { return eventRequest as T } } diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt index 6dc66090583..40f076f6ada 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt @@ -52,7 +52,7 @@ class KotlinFieldBreakpointType : JavaBreakpointType): Pair> { @@ -398,7 +397,7 @@ class KotlinCodeFragmentFactory: CodeFragmentFactory() { val sb = StringBuilder() - javaFile?.packageName?.check { !it.isBlank() }?.let { + javaFile?.packageName?.takeIf { !it.isBlank() }?.let { sb.append("package ").append(it.quoteIfNeeded()).append("\n") } diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt index 8006550080b..06adcfaec05 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt @@ -113,7 +113,7 @@ object KotlinEvaluationBuilder : EvaluatorBuilder { attachmentByPsiFile(codeFragment), Attachment("breakpoint.info", "line: ${position.line}")) - LOG.error("Trying to evaluate ${codeFragment.javaClass} with context ${codeFragment.context?.javaClass}", mergeAttachments(*attachments)) + LOG.error("Trying to evaluate ${codeFragment::class.java} with context ${codeFragment.context?.javaClass}", mergeAttachments(*attachments)) throw EvaluateExceptionUtil.createEvaluateException("Couldn't evaluate kotlin expression in this context") } diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilingEvaluator.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilingEvaluator.kt index 35a2f51a8a3..3250d405b09 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilingEvaluator.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilingEvaluator.kt @@ -75,7 +75,7 @@ private val LAMBDA_SUPERCLASSES = listOf( private class ClassBytes(val name: String) { val bytes: ByteArray by lazy { - val inputStream = this.javaClass.classLoader.getResourceAsStream(name.replace('.', '/') + ".class") + val inputStream = this::class.java.classLoader.getResourceAsStream(name.replace('.', '/') + ".class") ?: throw EvaluateException("Couldn't find $name class in current class loader") inputStream.use { diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt index e2b3ba85e5d..c18564cdcdb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/extractFunctionForDebuggerUtil.kt @@ -235,8 +235,7 @@ private fun getExpressionToAddDebugExpressionBefore(tmpFile: KtFile, contextElem private fun addDebugExpressionBeforeContextElement(codeFragment: KtCodeFragment, contextElement: PsiElement): List { val elementBefore = findElementBefore(contextElement) - val parent = elementBefore?.parent - if (parent == null || elementBefore == null) return emptyList() + val parent = elementBefore?.parent ?: return emptyList() val psiFactory = KtPsiFactory(codeFragment) diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinSteppingCommandProvider.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinSteppingCommandProvider.kt index 602fc25c000..6e456e0fd23 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinSteppingCommandProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/stepping/KotlinSteppingCommandProvider.kt @@ -476,7 +476,7 @@ private fun SuspendContextImpl.getXPositionForStepOutFromInlinedArgument( inlinedArgumentToSkip: KtFunctionLiteral ): XSourcePositionImpl? { return getNextPositionWithFilter(locations) { - offset, elementAt -> + offset, _ -> inlinedArgumentToSkip.textRange.contains(offset) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/editor/KotlinSmartEnterHandler.kt b/idea/src/org/jetbrains/kotlin/idea/editor/KotlinSmartEnterHandler.kt index f14ec9f53b6..cb9f7c69dbe 100644 --- a/idea/src/org/jetbrains/kotlin/idea/editor/KotlinSmartEnterHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/editor/KotlinSmartEnterHandler.kt @@ -163,4 +163,4 @@ class KotlinSmartEnterHandler: SmartEnterProcessorWithFixers() { private val BRANCH_CONTAINERS = TokenSet.create(KtNodeTypes.THEN, KtNodeTypes.ELSE, KtNodeTypes.BODY) private val BRACES = TokenSet.create(KtTokens.RBRACE, KtTokens.LBRACE) -private fun KtParameter.isInLambdaExpression() = this.parent?.parent is KtFunctionLiteral +private fun KtParameter.isInLambdaExpression() = this.parent.parent is KtFunctionLiteral diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt b/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt index 8077d0e799f..b60acffc38e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt @@ -162,7 +162,7 @@ fun parseCompilerArgumentsToFacet(arguments: List, defaultArguments: Lis with(kotlinFacet.configuration.settings) { val compilerArguments = this.compilerArguments ?: return - val defaultCompilerArguments = compilerArguments.javaClass.newInstance() + val defaultCompilerArguments = compilerArguments::class.java.newInstance() parseArguments(defaultArguments.toTypedArray(), defaultCompilerArguments, true) val oldCoroutineSupport = CoroutineSupport.byCompilerArguments(compilerArguments) @@ -182,7 +182,7 @@ fun parseCompilerArgumentsToFacet(arguments: List, defaultArguments: Lis fun exposeAsAdditionalArgument(field: Field) = field.name !in primaryFields && field.get(compilerArguments) != field.get(defaultCompilerArguments) - val additionalArgumentsString = with(compilerArguments.javaClass.newInstance()) { + val additionalArgumentsString = with(compilerArguments::class.java.newInstance()) { copyFieldsSatisfying(compilerArguments, this, ::exposeAsAdditionalArgument) ArgumentUtils.convertArgumentsToStringList(this).joinToString(separator = " ") { if (StringUtil.containsWhitespaces(it) || it.startsWith('"')) { @@ -193,7 +193,7 @@ fun parseCompilerArgumentsToFacet(arguments: List, defaultArguments: Lis compilerSettings?.additionalArguments = if (additionalArgumentsString.isNotEmpty()) additionalArgumentsString else CompilerSettings.DEFAULT_ADDITIONAL_ARGUMENTS - with(compilerArguments.javaClass.newInstance()) { + with(compilerArguments::class.java.newInstance()) { copyFieldsSatisfying(this, compilerArguments, ::exposeAsAdditionalArgument) } diff --git a/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinReferenceUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinReferenceUsageInfo.kt index ad7882ead0a..9f64cd4b80f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinReferenceUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/findUsages/KotlinReferenceUsageInfo.kt @@ -21,10 +21,10 @@ import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinReferenceUsageInfo(reference: PsiReference) : UsageInfo(reference) { - private val referenceType = reference.javaClass + private val referenceType = reference::class.java override fun getReference(): PsiReference? { val element = element ?: return null - return element.references.singleOrNull { it.javaClass == referenceType } + return element.references.singleOrNull { it::class.java == referenceType } } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt b/idea/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt index 03331c75bae..736e66527e2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt @@ -51,7 +51,6 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors import org.jetbrains.kotlin.resolve.source.getPsi -import org.jetbrains.kotlin.utils.addToStdlib.check abstract class KotlinFindMemberUsagesHandler protected constructor(declaration: T, elementsToSearch: Collection, factory: KotlinFindUsagesHandlerFactory) @@ -164,7 +163,7 @@ abstract class KotlinFindMemberUsagesHandler addTask { val overriders = HierarchySearchRequest(element, options.searchScope, true).searchOverriders() overriders.all { - val element = runReadAction { it.check { it.isValid }?.navigationElement } ?: return@all true + val element = runReadAction { it.takeIf { it.isValid }?.navigationElement } ?: return@all true KotlinFindUsagesHandler.processUsage(uniqueProcessor, element) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt b/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt index 78764aa3ab8..1b793f4d32a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt +++ b/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/OverridenFunctionMarker.kt @@ -51,7 +51,7 @@ private fun PsiMethod.isMethodWithDeclarationInOtherClass(): Boolean { internal fun getOverriddenDeclarations(mappingToJava: MutableMap, classes: Set): Set { val overridden = HashSet() for (aClass in classes) { - AllOverridingMethodsSearch.search(aClass)!!.forEach(object : Processor> { + AllOverridingMethodsSearch.search(aClass).forEach(object : Processor> { override fun process(pair: Pair?): Boolean { ProgressManager.checkCanceled() diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt index a198f794fd1..c6d941f0c2a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt @@ -36,7 +36,6 @@ import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTraceContext -import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.calls.CallResolver import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall @@ -47,8 +46,6 @@ import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes import org.jetbrains.kotlin.resolve.scopes.collectSyntheticMemberFunctions import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor import org.jetbrains.kotlin.types.TypeUtils -import org.jetbrains.kotlin.utils.addToStdlib.check -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class RedundantSamConstructorInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { @@ -179,7 +176,7 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() { for (staticFunWithSameName in containingClass.staticScope.getContributedFunctions(functionResolvedCall.resultingDescriptor.name, NoLookupLocation.FROM_IDE)) { if (staticFunWithSameName is SamAdapterDescriptor<*>) { if (isSamAdapterSuitableForCall(staticFunWithSameName, originalFunctionDescriptor, samConstructorCallArguments.size)) { - return samConstructorCallArguments.check { canBeReplaced(functionCall, it) } ?: emptyList() + return samConstructorCallArguments.takeIf { canBeReplaced(functionCall, it) } ?: emptyList() } } } @@ -187,13 +184,13 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() { // SAM adapters for member functions val syntheticScopes = functionCall.getResolutionFacade().getFrontendService(SyntheticScopes::class.java) val syntheticExtensions = syntheticScopes.collectSyntheticMemberFunctions( - containingClass.defaultType.singletonList(), - functionResolvedCall.resultingDescriptor.name, - NoLookupLocation.FROM_IDE) + listOf(containingClass.defaultType), + functionResolvedCall.resultingDescriptor.name, + NoLookupLocation.FROM_IDE) for (syntheticExtension in syntheticExtensions) { val samAdapter = syntheticExtension as? SamAdapterExtensionFunctionDescriptor ?: continue if (isSamAdapterSuitableForCall(samAdapter, originalFunctionDescriptor, samConstructorCallArguments.size)) { - return samConstructorCallArguments.check { canBeReplaced(functionCall, it) } ?: emptyList() + return samConstructorCallArguments.takeIf { canBeReplaced(functionCall, it) } ?: emptyList() } } @@ -204,7 +201,7 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() { = argument.toCallExpression()?.samConstructorValueArgument() != null private fun KtCallExpression.samConstructorValueArgument(): KtValueArgument? { - return valueArguments.singleOrNull()?.check { it.getArgumentExpression() is KtLambdaExpression } + return valueArguments.singleOrNull()?.takeIf { it.getArgumentExpression() is KtLambdaExpression } } private fun ValueArgument.toCallExpression(): KtCallExpression? { diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt index 8da4df30ea0..303eb3a58ae 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt @@ -69,7 +69,6 @@ import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.util.findCallableMemberBySignature -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets @@ -216,9 +215,9 @@ class UnusedSymbolInspection : AbstractKotlinInspection() { if (useScope is GlobalSearchScope) { var zeroOccurrences = true - for (name in listOf(declaration.name) + declaration.getAccessorNames() + declaration.getClassNameForCompanionObject().singletonOrEmptyList()) { + for (name in listOf(declaration.name) + declaration.getAccessorNames() + listOfNotNull(declaration.getClassNameForCompanionObject())) { if (name == null) continue - when (psiSearchHelper.isCheapEnoughToSearch(name!!, useScope, null, null)) { + when (psiSearchHelper.isCheapEnoughToSearch(name, useScope, null, null)) { ZERO_OCCURRENCES -> {} // go on, check other names FEW_OCCURRENCES -> zeroOccurrences = false TOO_MANY_OCCURRENCES -> return true // searching usages is too expensive; behave like it is used diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertAssertToIfWithThrowIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertAssertToIfWithThrowIntention.kt index 1a278600b75..73863dc9cb3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertAssertToIfWithThrowIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertAssertToIfWithThrowIntention.kt @@ -28,7 +28,6 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.check class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention(KtCallExpression::class.java, "Replace 'assert' with 'if' statement"), LowPriorityAction { override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean { @@ -93,7 +92,7 @@ class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention - singleStatement.check { it.isUsedAsExpression(bindingContext) } + singleStatement.takeIf { it.isUsedAsExpression(bindingContext) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertCamelCaseTestFunctionToSpacedIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertCamelCaseTestFunctionToSpacedIntention.kt index 009cfa2d118..d150256bb6a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertCamelCaseTestFunctionToSpacedIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertCamelCaseTestFunctionToSpacedIntention.kt @@ -112,7 +112,7 @@ class ConvertCamelCaseTestFunctionToSpacedIntention : SelfTargetingRangeIntentio override fun beforeTemplateFinished(state: TemplateState?, template: Template?) { val varName = (template as? TemplateImpl)?.getVariableNameAt(0) ?: return chosenId = state?.getVariableValue(varName)?.text?.quoteIfNeeded() ?: return - range = state?.getVariableRange(varName) + range = state.getVariableRange(varName) } override fun templateFinished(template: Template?, brokenOff: Boolean) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt index a448b18c1d8..403d13d2cb7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt @@ -37,7 +37,6 @@ import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention( KtObjectLiteralExpression::class.java, @@ -84,7 +83,7 @@ class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention Unit ) { - val descriptor = descriptorWithConflicts.descriptor.copy(suggestedNames = className.singletonList()) + val descriptor = descriptorWithConflicts.descriptor.copy(suggestedNames = listOf(className)) doRefactor( ExtractionGeneratorConfiguration(descriptor, ExtractionGeneratorOptions.DEFAULT), onFinish diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToExpressionBodyIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToExpressionBodyIntention.kt index fe4d089c3e5..c8e1ab4cbc8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToExpressionBodyIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToExpressionBodyIntention.kt @@ -30,7 +30,6 @@ import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.utils.addToStdlib.check class ConvertToExpressionBodyIntention( val convertEmptyToUnit: Boolean = true @@ -62,7 +61,7 @@ class ConvertToExpressionBodyIntention( val deleteTypeHandler: (KtCallableDeclaration) -> Unit = { it.deleteChildRange(it.colon!!, it.typeReference!!) } - applyTo(declaration, deleteTypeHandler.check { canDeleteTypeRef }) + applyTo(declaration, deleteTypeHandler.takeIf { canDeleteTypeRef }) } private fun applyTo(declaration: KtDeclarationWithBody, deleteTypeHandler: ((KtCallableDeclaration) -> Unit)?) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt index 9673b545996..ee15047e1b8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt @@ -42,7 +42,6 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.util.* class DestructureInspection : IntentionBasedInspection( @@ -66,7 +65,7 @@ class DestructureIntention : SelfTargetingRangeIntention( val factory = KtPsiFactory(element) val validator = NewDeclarationNameValidator( container = element.parent, anchor = element, target = NewDeclarationNameValidator.Target.VARIABLES, - excludedDeclarations = usagesToRemove.map { it.declarationToDrop.singletonOrEmptyList() }.flatten() + excludedDeclarations = usagesToRemove.map { listOfNotNull(it.declarationToDrop) }.flatten() ) val names = ArrayList() usagesToRemove.forEach { (descriptor, usagesToReplace, variableToDrop, name) -> diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt index 331c5c07d5e..556af913e69 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt @@ -53,7 +53,6 @@ import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor import org.jetbrains.kotlin.util.findCallableMemberBySignature -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* import javax.swing.ListSelectionModel @@ -129,7 +128,7 @@ abstract class ImplementAbstractMemberIntentionBase : descriptorToImplement, OverrideMemberChooserObject.BodyType.EMPTY, preferConstructorParameters) - OverrideImplementMembersHandler.generateMembers(editor, targetClass, chooserObject.singletonList(), false) + OverrideImplementMembersHandler.generateMembers(editor, targetClass, listOf(chooserObject), false) } private fun implementInJavaClass(member: KtNamedDeclaration, targetClass: PsiClass) { @@ -204,7 +203,7 @@ abstract class ImplementAbstractMemberIntentionBase : ) { findClassesToProcess(element).toList() } ?: return if (classesToProcess.isEmpty()) return - classesToProcess.singleOrNull()?.let { return implementInClass(element, it.singletonList()) } + classesToProcess.singleOrNull()?.let { return implementInClass(element, listOf(it)) } val renderer = ClassRenderer() val sortedClasses = classesToProcess.sortedWith(renderer.comparator) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt index b2877deb0de..ad8f5c8c396 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt @@ -34,7 +34,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class IterateExpressionIntention : SelfTargetingIntention(KtExpression::class.java, "Iterate over collection"), HighPriorityAction { override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean { @@ -77,7 +76,7 @@ class IterateExpressionIntention : SelfTargetingIntention(KtExpres componentFunctions.map { suggestNamesForComponent(it, project, collectingValidator) } } else { - KotlinNameSuggester.suggestIterationVariableNames(element, elementType, bindingContext, nameValidator, "e").singletonList() + listOf(KotlinNameSuggester.suggestIterationVariableNames(element, elementType, bindingContext, nameValidator, "e")) } val paramPattern = (names.singleOrNull()?.first() @@ -87,7 +86,7 @@ class IterateExpressionIntention : SelfTargetingIntention(KtExpres CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(forExpression)?.let { forExpression -> val bodyPlaceholder = (forExpression.body as KtBlockExpression).statements.single() - val parameters = forExpression.destructuringDeclaration?.entries ?: forExpression.loopParameter!!.singletonList() + val parameters = forExpression.destructuringDeclaration?.entries ?: listOf(forExpression.loopParameter!!) val templateBuilder = TemplateBuilderImpl(forExpression) for ((parameter, parameterNames) in (parameters zip names)) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveBracesIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveBracesIntention.kt index 6409a7f1691..7488de1c847 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveBracesIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveBracesIntention.kt @@ -55,7 +55,7 @@ class RemoveBracesIntention : SelfTargetingIntention(KtElement::class val block = element.findChildBlock() ?: return val statement = block.statements.single() - val container = block.parent!! + val container = block.parent val construct = container.parent as KtExpression handleComments(construct, block) @@ -76,8 +76,8 @@ class RemoveBracesIntention : SelfTargetingIntention(KtElement::class if (construct.prevSibling is PsiWhiteSpace) { construct.prevSibling!!.replace(psiFactory.createNewLine()) } - val commentElement = construct.parent!!.addBefore(sibling, construct.prevSibling) - construct.parent!!.addBefore(psiFactory.createNewLine(), commentElement) + val commentElement = construct.parent.addBefore(sibling, construct.prevSibling) + construct.parent.addBefore(psiFactory.createNewLine(), commentElement) } sibling = sibling.nextSibling } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt index 25f76df2eae..49982aa431c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt @@ -64,6 +64,6 @@ class RemoveExplicitTypeIntention : SelfTargetingRangeIntention(KtExpression::clas if (expression.operationToken != operator) return false } - val ifExpression = expression.parent?.parent as? KtIfExpression ?: return false + val ifExpression = expression.parent.parent as? KtIfExpression ?: return false if (ifExpression.condition == null) return false if (!PsiTreeUtil.isAncestor(ifExpression.condition, element, false)) return false diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/Utils.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/Utils.kt index ce22d3c7eab..5074c3e148a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/Utils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/Utils.kt @@ -64,7 +64,7 @@ fun isAutoCreatedItUsage(expression: KtNameReferenceExpression): Boolean { // returns assignment which replaces initializer fun splitPropertyDeclaration(property: KtProperty): KtBinaryExpression { - val parent = property.parent!! + val parent = property.parent val initializer = property.initializer!! diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt index bbe66cebed8..10e41239523 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.idea.intentions.branchedTransformations import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis -import org.jetbrains.kotlin.utils.addToStdlib.check object BranchedFoldingUtils { fun getFoldableBranchedAssignment(branch: KtExpression?): KtBinaryExpression? { @@ -36,11 +35,11 @@ object BranchedFoldingUtils { return true } - return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.check(::checkAssignment) + return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.takeIf(::checkAssignment) } fun getFoldableBranchedReturn(branch: KtExpression?): KtReturnExpression? { - return (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.check { it.returnedExpression != null } + return (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.takeIf { it.returnedExpression != null } } fun checkAssignmentsMatch(a1: KtBinaryExpression, a2: KtBinaryExpression): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithBinaryOperatorIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithBinaryOperatorIntention.kt index 06a713ecf90..aaf3a8ce9fc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithBinaryOperatorIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithBinaryOperatorIntention.kt @@ -109,7 +109,7 @@ class ReplaceCallWithBinaryOperatorIntention : SelfTargetingRangeIntention { val resolvedCall = dotQualified.toResolvedCall(BodyResolveMode.PARTIAL) ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt index e2c7d85b7cf..99e0d542cd1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt @@ -83,7 +83,7 @@ class ReplaceContainsIntention : SelfTargetingRangeIntention = listOf( @@ -138,7 +137,7 @@ fun match(loop: KtForExpression, useLazySequence: Boolean): MatchResult? { return MatchResult(sequenceExpression, result, state.initializationStatementsToDelete) - .check { checkSmartCastsPreserved(loop, it) } + .takeIf { checkSmartCastsPreserved(loop, it) } } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt index c7b533b099e..3ccce0896a4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt @@ -28,7 +28,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.types.typeUtil.TypeNullability import org.jetbrains.kotlin.types.typeUtil.nullability -import org.jetbrains.kotlin.utils.addToStdlib.check /** * Matches: @@ -361,8 +360,8 @@ object FindTransformationMatcher : TransformationMatcher { if (this !is KtBinaryExpression) return null if (operationToken != KtTokens.EQEQ) return null return when { - left.isVariableReference(inputVariable) -> right?.check { it.isStableInLoop(loop, false) } - right.isVariableReference(inputVariable) -> left?.check { it.isStableInLoop(loop, false) } + left.isVariableReference(inputVariable) -> right?.takeIf { it.isStableInLoop(loop, false) } + right.isVariableReference(inputVariable) -> left?.takeIf { it.isStableInLoop(loop, false) } else -> null } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt index e59b58f0010..fbe2887b410 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt @@ -21,7 +21,6 @@ import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.MapTransfor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle -import org.jetbrains.kotlin.utils.singletonOrEmptyList class MaxOrMinTransformation( loop: KtForExpression, @@ -133,7 +132,7 @@ class MaxOrMinTransformation( MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, value, mapNotNull = false) val transformation = MaxOrMinTransformation(state.outerLoop, variableInitialization, isMax) - return TransformationMatch.Result(transformation, mapTransformation.singletonOrEmptyList()) + return TransformationMatch.Result(transformation, listOfNotNull(mapTransformation)) } private fun match( diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt index b5f03074fb5..1407755d967 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt @@ -29,7 +29,6 @@ import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* abstract class FilterTransformationBase : SequenceTransformation { @@ -119,7 +118,7 @@ abstract class FilterTransformationBase : SequenceTransformation { restStatements: List ): List { if (conditions.size == 1) { - return createFilterTransformation(loop, inputVariable, indexVariable, conditions.single()).singletonList() + return listOf(createFilterTransformation(loop, inputVariable, indexVariable, conditions.single())) } var transformations = conditions.map { createFilterTransformation(loop, inputVariable, indexVariable, it) } @@ -165,12 +164,12 @@ abstract class FilterTransformationBase : SequenceTransformation { else if (state.statements.size == 1) { val thenStatement = thenBranch.blockExpressionsOrSingle().singleOrNull() if (thenStatement is KtBreakExpression || thenStatement is KtContinueExpression) { - return matchOneTransformation(state, condition, false, thenBranch, elseBranch.singletonList()) + return matchOneTransformation(state, condition, false, thenBranch, listOf(elseBranch)) } val elseStatement = elseBranch.blockExpressionsOrSingle().singleOrNull() if (elseStatement is KtBreakExpression || elseStatement is KtContinueExpression) { - return matchOneTransformation(state, condition, true, elseBranch, thenBranch.singletonList()) + return matchOneTransformation(state, condition, true, elseBranch, listOf(thenBranch)) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt index 288059216e3..2929bc9d60f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt @@ -38,13 +38,10 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiUtil.isOrdinaryAssignment import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.DelegatingBindingTrace -import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* fun generateLambda(inputVariable: KtCallableDeclaration, expression: KtExpression): KtLambdaExpression { @@ -166,7 +163,7 @@ fun KtExpression?.findVariableInitializationBeforeLoop( for (statement in prevStatements) { val variableInitialization = extractVariableInitialization(statement, variable) if (variableInitialization != null) { - return variableInitialization.check { + return variableInitialization.takeIf { statementsBetween.all { canSwapExecutionOrder(variableInitialization.initializationStatement, it) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessings.kt b/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessings.kt index 75ac0ce7ff7..44d8fafcf6b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessings.kt +++ b/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessings.kt @@ -81,7 +81,7 @@ object J2KPostProcessingRegistrar { registerIntentionBasedProcessing(DestructureIntention()) registerIntentionBasedProcessing(SimplifyAssertNotNullIntention()) - registerDiagnosticBasedProcessing(Errors.USELESS_CAST) { element, diagnostic -> + registerDiagnosticBasedProcessing(Errors.USELESS_CAST) { element, _ -> val expression = RemoveUselessCastFix.invoke(element) val variable = expression.parent as? KtProperty @@ -94,12 +94,12 @@ object J2KPostProcessingRegistrar { } } - registerDiagnosticBasedProcessing(Errors.REDUNDANT_PROJECTION) { element, diagnostic -> + registerDiagnosticBasedProcessing(Errors.REDUNDANT_PROJECTION) { _, diagnostic -> val fix = RemoveModifierFix.createRemoveProjectionFactory(true).createActions(diagnostic).single() as RemoveModifierFix fix.invoke() } - registerDiagnosticBasedProcessing(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, diagnostic -> + registerDiagnosticBasedProcessing(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ -> val exclExclExpr = element.parent as KtUnaryExpression exclExclExpr.replace(exclExclExpr.baseExpression!!) } @@ -107,7 +107,7 @@ object J2KPostProcessingRegistrar { registerDiagnosticBasedProcessingFactory( Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION ) { - element: KtSimpleNameExpression, diagnostic: Diagnostic -> + element: KtSimpleNameExpression, _: Diagnostic -> val property = element.mainReference.resolve() as? KtProperty if (property == null) { null diff --git a/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessor.kt index a2914217b92..8979174b550 100644 --- a/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/j2k/J2kPostProcessor.kt @@ -51,7 +51,7 @@ class J2kPostProcessor(private val formatCode: Boolean) : PostProcessor { while (elementToActions.isNotEmpty()) { var modificationStamp: Long? = file.modificationStamp - for ((element, action, processing) in elementToActions) { + for ((element, action, _) in elementToActions) { if (element.isValid) { action() } diff --git a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt index 42e5b77c532..683423bba80 100644 --- a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt @@ -69,7 +69,7 @@ class JoinDeclarationAndAssignmentHandler : JoinRawLinesHandlerDelegate { private fun doJoin(property: KtProperty, assignment: KtBinaryExpression) { property.initializer = assignment.right - property.parent!!.deleteChildRange(property.nextSibling, assignment) //TODO: should we delete range? + property.parent.deleteChildRange(property.nextSibling, assignment) //TODO: should we delete range? } private fun isToSkip(element: PsiElement): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt b/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt index 785dd6b37e1..9d1ea9ba874 100644 --- a/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt +++ b/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt @@ -42,7 +42,7 @@ object KotlinPatterns: StandardPatterns() { @Suppress("unused") open class KotlinFunctionPattern : PsiElementPattern(KtFunction::class.java) { fun withParameters(vararg parameterTypes: String): KotlinFunctionPattern { - return withPatternCondition("kotlinFunctionPattern-withParameters") { function, context -> + return withPatternCondition("kotlinFunctionPattern-withParameters") { function, _ -> if (function.valueParameters.size != parameterTypes.size) return@withPatternCondition false val descriptor = function.resolveToDescriptorIfAny() as? FunctionDescriptor ?: return@withPatternCondition false @@ -63,7 +63,7 @@ open class KotlinFunctionPattern : PsiElementPattern + return withPatternCondition("kotlinFunctionPattern-withReceiver") { function, _ -> if (function.receiverTypeReference == null) return@withPatternCondition false if (receiverFqName == "?") return@withPatternCondition true @@ -75,7 +75,7 @@ open class KotlinFunctionPattern : PsiElementPattern + return withPatternCondition("kotlinFunctionPattern-definedInClass") { function, _ -> if (function.parent is KtFile) return@withPatternCondition false function.containingClassOrObject?.fqName?.asString() == fqName @@ -83,7 +83,7 @@ open class KotlinFunctionPattern : PsiElementPattern + return withPatternCondition("kotlinFunctionPattern-definedInPackage") { function, _ -> if (function.parent !is KtFile) return@withPatternCondition false function.containingKtFile.packageFqName.asString() == packageFqName @@ -114,7 +114,7 @@ class KtParameterPattern : PsiElementPattern(Kt } fun withAnnotation(fqName: String): KtParameterPattern { - return withPatternCondition("KtParameterPattern-withAnnotation") { ktParameter, context -> + return withPatternCondition("KtParameterPattern-withAnnotation") { ktParameter, _ -> if (ktParameter.annotationEntries.isEmpty()) return@withPatternCondition false val parameterDescriptor = ktParameter.resolveToDescriptorIfAny() as? ValueParameterDescriptor ?: return@withPatternCondition false diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt index 8f24e87e825..351696ae9b1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt @@ -35,7 +35,6 @@ import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.Constrain import org.jetbrains.kotlin.resolve.calls.inference.filterConstraintsOut import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.utils.singletonOrEmptyList class AddGenericUpperBoundFix( typeParameter: KtTypeParameter, @@ -68,7 +67,7 @@ class AddGenericUpperBoundFix( return when (diagnostic.factory) { Errors.UPPER_BOUND_VIOLATED -> { val upperBoundViolated = Errors.UPPER_BOUND_VIOLATED.cast(diagnostic) - createAction(upperBoundViolated.b, upperBoundViolated.a).singletonOrEmptyList() + listOfNotNull(createAction(upperBoundViolated.b, upperBoundViolated.a)) } Errors.TYPE_INFERENCE_UPPER_BOUND_VIOLATED -> { val inferenceData = Errors.TYPE_INFERENCE_UPPER_BOUND_VIOLATED.cast(diagnostic).a diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeCallableReturnTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeCallableReturnTypeFix.kt index 68b43d4c558..8bad035bcb0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeCallableReturnTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeCallableReturnTypeFix.kt @@ -46,7 +46,6 @@ import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isUnit -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* abstract class ChangeCallableReturnTypeFix( @@ -76,7 +75,7 @@ abstract class ChangeCallableReturnTypeFix( val name = element.name if (name != null) { val container = element.resolveToDescriptor().containingDeclaration as? ClassDescriptor - val containerName = container?.name?.check { !it.isSpecial }?.asString() + val containerName = container?.name?.takeIf { !it.isSpecial }?.asString() val fullName = if (containerName != null) "'$containerName.$name'" else "'$name'" if (element is KtParameter) { return "property $fullName" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeMemberFunctionSignatureFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeMemberFunctionSignatureFix.kt index f1d0893aa11..c0f4db1c82a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeMemberFunctionSignatureFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeMemberFunctionSignatureFix.kt @@ -46,7 +46,6 @@ import org.jetbrains.kotlin.resolve.findMemberWithMaxVisibility import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.supertypes -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* /** @@ -254,7 +253,7 @@ class ChangeMemberFunctionSignatureFix private constructor( object MatchNames : ParameterChooser { override fun choose(parameter: ValueParameterDescriptor, superParameter: ValueParameterDescriptor): ValueParameterDescriptor? { - return superParameter.check { parameter.name == superParameter.name } + return superParameter.takeIf { parameter.name == superParameter.name } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt index b3d121e8a72..542310e4937 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableTypeFix.kt @@ -38,7 +38,6 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* open class ChangeVariableTypeFix(element: KtVariableDeclaration, type: KotlinType) : KotlinQuickFixAction(element) { @@ -51,7 +50,7 @@ open class ChangeVariableTypeFix(element: KtVariableDeclaration, type: KotlinTyp val name = element.name if (name != null) { val container = element.resolveToDescriptor().containingDeclaration as? ClassDescriptor - val containerName = container?.name?.check { !it.isSpecial }?.asString() + val containerName = container?.name?.takeIf { !it.isSpecial }?.asString() return if (containerName != null) "'$containerName.$name'" else "'$name'" } else { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ImportFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ImportFix.kt index 0e2a9ac87ec..b90d28e718f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ImportFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ImportFix.kt @@ -76,8 +76,6 @@ import org.jetbrains.kotlin.resolve.scopes.utils.addImportingScope import org.jetbrains.kotlin.resolve.scopes.utils.collectFunctions import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.CachedValueProperty -import org.jetbrains.kotlin.utils.addToStdlib.singletonList -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* /** @@ -201,7 +199,7 @@ internal abstract class ImportFixBase protected constructor( .any { diagnostic -> diagnostic.factory in getSupportedErrors() } } - protected open fun elementsToCheckDiagnostics(): Collection = element.singletonOrEmptyList() + protected open fun elementsToCheckDiagnostics(): Collection = listOfNotNull(element) abstract fun fillCandidates( name: String, @@ -264,7 +262,7 @@ internal class ImportFix(expression: KtSimpleNameExpression) : OrdinaryImportFix if (element.getIdentifier() != null) { val name = element.getReferencedName() if (Name.isValidIdentifier(name)) { - return Name.identifier(name).singletonList() + return listOf(Name.identifier(name)) } } @@ -356,7 +354,7 @@ internal class ImportConstructorReferenceFix(expression: KtSimpleNameExpression) } internal class InvokeImportFix(expression: KtExpression) : OrdinaryImportFixBase(expression, MyFactory) { - override val importNames = OperatorNameConventions.INVOKE.singletonList() + override val importNames = listOf(OperatorNameConventions.INVOKE) override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.OPERATOR(it) } @@ -393,7 +391,7 @@ internal open class ArrayAccessorImportFix( val element = diagnostic.psiElement if (element is KtArrayAccessExpression && element.arrayExpression != null) { - return ArrayAccessorImportFix(element, importName(diagnostic).singletonList(), true).apply { computeSuggestions() } + return ArrayAccessorImportFix(element, listOf(importName(diagnostic)), true).apply { computeSuggestions() } } return null @@ -430,14 +428,14 @@ internal class DelegateAccessorsImportFix( override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction? { return (diagnostic.psiElement as? KtExpression)?.let { - DelegateAccessorsImportFix(it, importNames(diagnostic.singletonList()), false).apply { computeSuggestions() } + DelegateAccessorsImportFix(it, importNames(listOf(diagnostic)), false).apply { computeSuggestions() } } } override fun doCreateActionsForAllProblems(sameTypeDiagnostics: Collection): List { val element = sameTypeDiagnostics.first().psiElement val names = importNames(sameTypeDiagnostics) - return (element as? KtExpression)?.let { DelegateAccessorsImportFix(it, names, true) }.singletonOrEmptyList() + return listOfNotNull((element as? KtExpression)?.let { DelegateAccessorsImportFix(it, names, true) }) } } } @@ -464,7 +462,7 @@ internal class ComponentsImportFix( override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction? { return (diagnostic.psiElement as? KtExpression)?.let { - ComponentsImportFix(it, importNames(diagnostic.singletonList()), false).apply { computeSuggestions() } + ComponentsImportFix(it, importNames(listOf(diagnostic)), false).apply { computeSuggestions() } } } @@ -472,7 +470,7 @@ internal class ComponentsImportFix( val element = sameTypeDiagnostics.first().psiElement val names = importNames(sameTypeDiagnostics) val solveSeveralProblems = sameTypeDiagnostics.size > 1 - return (element as? KtExpression)?.let { ComponentsImportFix(it, names, solveSeveralProblems) }.singletonOrEmptyList() + return listOfNotNull((element as? KtExpression)?.let { ComponentsImportFix(it, names, solveSeveralProblems) }) } } } @@ -490,8 +488,8 @@ internal class ImportForMismatchingArgumentsFix( return callExpression.valueArguments + callExpression.valueArguments.mapNotNull { it.getArgumentExpression() } + callExpression.valueArguments.mapNotNull { it.getArgumentName()?.referenceExpression } + - callExpression.valueArgumentList.singletonOrEmptyList() + - callExpression.referenceExpression().singletonOrEmptyList() + listOfNotNull(callExpression.valueArgumentList) + + listOfNotNull(callExpression.referenceExpression()) } override fun fillCandidates( @@ -571,8 +569,8 @@ object ImportForMissingOperatorFactory : KotlinSingleIntentionActionFactory() { when (name) { OperatorNameConventions.GET, OperatorNameConventions.SET -> { if (element is KtArrayAccessExpression) { - return object : ArrayAccessorImportFix(element, name.singletonList(), false) { - override fun getSupportedErrors() = Errors.OPERATOR_MODIFIER_REQUIRED.singletonList() + return object : ArrayAccessorImportFix(element, listOf(name), false) { + override fun getSupportedErrors() = listOf(Errors.OPERATOR_MODIFIER_REQUIRED) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt index ce40352d173..7dcb7cb7fce 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt @@ -25,7 +25,6 @@ import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.utils.addToStdlib.singletonList abstract class KotlinSingleIntentionActionFactoryWithDelegate( private val actionPriority: IntentionActionPriority = IntentionActionPriority.NORMAL @@ -38,11 +37,11 @@ abstract class KotlinSingleIntentionActionFactoryWithDelegate D? ): List { - return QuickFixWithDelegateFactory(actionPriority) factory@ { + return listOf(QuickFixWithDelegateFactory(actionPriority) factory@ { val originalElement = originalElementPointer.element ?: return@factory null val data = quickFixDataFactory() ?: return@factory null createFix(originalElement, data) - }.singletonList() + }) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinSingleIntentionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinSingleIntentionActionFactory.kt index 37b38a153ab..aaddf121d8e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinSingleIntentionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinSingleIntentionActionFactory.kt @@ -19,10 +19,8 @@ package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import org.jetbrains.kotlin.diagnostics.Diagnostic -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList - abstract class KotlinSingleIntentionActionFactory : KotlinIntentionActionsFactory() { protected abstract fun createAction(diagnostic: Diagnostic): IntentionAction? - final override fun doCreateActions(diagnostic: Diagnostic): List = createAction(diagnostic).singletonOrEmptyList() + final override fun doCreateActions(diagnostic: Diagnostic): List = listOfNotNull(createAction(diagnostic)) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt index 9e4896fe5cc..df300e78330 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt @@ -49,7 +49,7 @@ class LiftAssignmentOutOfTryFix(element: KtTryExpression): KotlinQuickFixAction< override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement as? KtExpression ?: return null - val originalCatch = expression.parent?.parent?.parent as? KtCatchClause ?: return null + val originalCatch = expression.parent.parent?.parent as? KtCatchClause ?: return null val tryExpression = originalCatch.parent as? KtTryExpression ?: return null val tryAssignment = BranchedFoldingUtils.getFoldableBranchedAssignment(tryExpression.tryBlock) ?: return null for (catchClause in tryExpression.catchClauses) { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt index e8de437a614..7dc3a5b7320 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt @@ -57,7 +57,7 @@ open class QuickFixWithDelegateFactory( val action = delegateFactory() ?: return assert(action.detectPriority() == this.detectPriority()) { - "Incorrect priority of QuickFixWithDelegateFactory wrapper for ${action.javaClass.name}" + "Incorrect priority of QuickFixWithDelegateFactory wrapper for ${action::class.java.name}" } action.invoke(project, editor, file) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveSingleLambdaParameterFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveSingleLambdaParameterFix.kt index dbc59a99cab..7f2cdd59426 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveSingleLambdaParameterFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveSingleLambdaParameterFix.kt @@ -47,7 +47,7 @@ class RemoveSingleLambdaParameterFix(element: KtParameter) : KotlinQuickFixActio if (parameterList.parameters.size != 1) return null - if (parameterList.parent?.parent !is KtLambdaExpression) return null + if (parameterList.parent.parent !is KtLambdaExpression) return null return RemoveSingleLambdaParameterFix(parameter) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithNullCheckFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithNullCheckFix.kt index 9669b317ec2..2ab0fa6e820 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithNullCheckFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithNullCheckFix.kt @@ -87,7 +87,7 @@ class SurroundWithNullCheckFix( override fun createAction(diagnostic: Diagnostic): IntentionAction? { val nullableExpression = diagnostic.psiElement as? KtReferenceExpression ?: return null - val forExpression = nullableExpression.parent?.parent as? KtForExpression ?: return null + val forExpression = nullableExpression.parent.parent as? KtForExpression ?: return null if (forExpression.parent !is KtBlockExpression) return null if (!nullableExpression.isStable()) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/WholeProjectModalAction.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/WholeProjectModalAction.kt index ef08fdf605b..1b1fa172229 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/WholeProjectModalAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/WholeProjectModalAction.kt @@ -34,7 +34,6 @@ import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtVisitorVoid import org.jetbrains.kotlin.psi.psiUtil.flatMapDescendantsOfTypeVisitor -import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.util.* abstract class WholeProjectModalAction(val title: String) : IntentionAction { @@ -140,7 +139,7 @@ internal class WholeProjectForEachElementOfTypeFix private construc noinline taskProcessor: (TTask) -> Unit, name: String ) = createForMultiTaskOnElement( - tasksFactory = { taskFactory(it).singletonOrEmptyList() }, + tasksFactory = { listOfNotNull(taskFactory(it)) }, tasksProcessor = { it.forEach(taskProcessor) }, name = name ) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt index 9aa9da1f579..4f3bce2a224 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt @@ -72,7 +72,6 @@ import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isUnit -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.lang.AssertionError import java.lang.IllegalArgumentException import java.lang.IllegalStateException @@ -301,7 +300,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) { .subtract(substitutionMap.keys) fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap) - mandatoryTypeParametersAsCandidates = receiverTypeCandidate.singletonOrEmptyList() + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } + mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } } else { fakeFunction = null @@ -902,7 +901,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) { // file templates val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset(jetFileToEdit, declarationMarker.startOffset, - declaration.javaClass, + declaration::class.java, false) ?: return runWriteAction { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt index f1a3e3767d4..7f52b510f86 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt @@ -26,7 +26,6 @@ import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.Callab import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.PropertyInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable.CreateParameterFromUsageFix import org.jetbrains.kotlin.psi.KtElement -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* abstract class CreateCallableMemberFromUsageFactory( @@ -48,7 +47,7 @@ abstract class CreateCallableMemberFromUsageFactory( protected open fun createCallableInfo(element: E, diagnostic: Diagnostic): CallableInfo? = null override fun extractFixData(element: E, diagnostic: Diagnostic): List - = createCallableInfo(element, diagnostic).singletonOrEmptyList() + = listOfNotNull(createCallableInfo(element, diagnostic)) override fun createFixes( originalElementPointer: SmartPsiElementPointer, diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromCallWithConstructorCalleeActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromCallWithConstructorCalleeActionFactory.kt index 1c2b047faca..8b2870b5035 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromCallWithConstructorCalleeActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromCallWithConstructorCalleeActionFactory.kt @@ -25,7 +25,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* object CreateClassFromCallWithConstructorCalleeActionFactory : CreateClassFromUsageFactory() { @@ -46,7 +45,7 @@ object CreateClassFromCallWithConstructorCalleeActionFactory : CreateClassFromUs } override fun getPossibleClassKinds(element: KtCallElement, diagnostic: Diagnostic): List { - return (if (element is KtAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS).singletonList() + return listOf((if (element is KtAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS)) } override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): ClassInfo? { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromConstructorCallActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromConstructorCallActionFactory.kt index 93652bca6c1..95cded102b3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromConstructorCallActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromConstructorCallActionFactory.kt @@ -26,7 +26,6 @@ import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.calls.callUtil.getCall import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageFactory() { @@ -50,7 +49,7 @@ object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageFactory< val fullCallExpr = element.getQualifiedExpressionForSelectorOrThis() if (!fullCallExpr.getInheritableTypeInfo(context, moduleDescriptor, targetParent).second(classKind)) return emptyList() - return classKind.singletonList() + return listOf(classKind) } override fun extractFixData(element: KtCallExpression, diagnostic: Diagnostic): ClassInfo? { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt index 45b3ad5f3fd..2b947f279a5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt @@ -36,13 +36,13 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac } private fun getFullCallExpression(element: KtSimpleNameExpression): KtExpression? { - return element.parent?.let { + return element.parent.let { when { it is KtCallExpression && it.calleeExpression == element -> return null it is KtQualifiedExpression && it.selectorExpression == element -> it else -> element } - } as? KtExpression + } } private fun isQualifierExpected(element: KtSimpleNameExpression) = element.isDotReceiver() || ((element.parent as? KtDotQualifiedExpression)?.isDotReceiver() ?: false) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt index 5a4587746f7..7951ccae43f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt @@ -32,7 +32,7 @@ object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory { - val typeRefParent = element.parent?.parent + val typeRefParent = element.parent.parent if (typeRefParent is KtConstructorCalleeExpression) return Collections.emptyList() val interfaceExpected = typeRefParent is KtSuperTypeEntry @@ -60,7 +60,7 @@ object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory null } @@ -88,16 +88,16 @@ internal fun KtExpression.getInheritableTypeInfo( moduleDescriptor: ModuleDescriptor, containingDeclaration: PsiElement): Pair Boolean> { val types = guessTypes(context, moduleDescriptor, coerceUnusedToUnit = false) - if (types.size != 1) return TypeInfo.Empty to { classKind -> true } + if (types.size != 1) return TypeInfo.Empty to { _ -> true } val type = types.first() - val descriptor = type.constructor.declarationDescriptor ?: return TypeInfo.Empty to { classKind -> false } + val descriptor = type.constructor.declarationDescriptor ?: return TypeInfo.Empty to { _ -> false } val canHaveSubtypes = !(type.constructor.isFinal || type.containsStarProjections()) val isEnum = DescriptorUtils.isEnumClass(descriptor) if (!(canHaveSubtypes || isEnum) - || descriptor is TypeParameterDescriptor) return TypeInfo.Empty to { classKind -> false } + || descriptor is TypeParameterDescriptor) return TypeInfo.Empty to { _ -> false } return TypeInfo.ByType(type, Variance.OUT_VARIANCE).noSubstitutions() to { classKind -> when (classKind) { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterUnmatchedTypeArgumentActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterUnmatchedTypeArgumentActionFactory.kt index a6ed39b22da..15d17fdb5ae 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterUnmatchedTypeArgumentActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterUnmatchedTypeArgumentActionFactory.kt @@ -34,7 +34,6 @@ import org.jetbrains.kotlin.psi.KtUserType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier -import org.jetbrains.kotlin.utils.addToStdlib.singletonList object CreateTypeParameterUnmatchedTypeArgumentActionFactory : KotlinIntentionActionFactoryWithDelegate() { override fun getElementOfInterest(diagnostic: Diagnostic) = diagnostic.psiElement as? KtTypeArgumentList @@ -77,10 +76,10 @@ object CreateTypeParameterUnmatchedTypeArgumentActionFactory : KotlinIntentionAc diagnostic: Diagnostic, quickFixDataFactory: () -> CreateTypeParameterData? ): List { - return QuickFixWithDelegateFactory factory@ { + return listOf(QuickFixWithDelegateFactory factory@ { val originalElement = originalElementPointer.element ?: return@factory null val data = quickFixDataFactory() ?: return@factory null CreateTypeParameterFromUsageFix(originalElement, data, false) - }.singletonList() + }) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt index e3d2fbd085c..241503b2d57 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt @@ -33,7 +33,6 @@ import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElement import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.types.Variance -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* object CreateLocalVariableActionFactory: KotlinSingleIntentionActionFactory() { @@ -72,7 +71,7 @@ object CreateLocalVariableActionFactory: KotlinSingleIntentionActionFactory() { ) val propertyInfo = PropertyInfo(propertyName, TypeInfo.Empty, typeInfo, varExpected, Collections.singletonList(actualContainer)) - with (CallableBuilderConfiguration(propertyInfo.singletonOrEmptyList(), originalElement, file, editor).createBuilder()) { + with (CallableBuilderConfiguration(listOfNotNull(propertyInfo), originalElement, file, editor).createBuilder()) { placement = CallablePlacement.NoReceiver(actualContainer) project.executeCommand(text) { build() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt index d8c343e3c38..6d13fc5ffba 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt @@ -89,7 +89,7 @@ object CreateParameterByRefActionFactory : CreateParameterFromUsageFactory chooseContainingClass(it) - it is KtAnonymousInitializer -> it.parent?.parent as? KtClass + it is KtAnonymousInitializer -> it.parent.parent as? KtClass it is KtSuperTypeListEntry -> { val klass = it.getStrictParentOfType() if (klass is KtClass && !klass.isInterface() && klass !is KtEnumEntry) klass else null diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt index 8d1454228de..4a04037569e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeInfo.kt @@ -50,7 +50,6 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform import org.jetbrains.kotlin.types.typeUtil.isUnit -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import org.jetbrains.kotlin.utils.keysToMap import java.util.* @@ -78,7 +77,7 @@ open class KotlinChangeInfo( private val originalReceiverTypeInfo = methodDescriptor.receiver?.originalTypeInfo var receiverParameterInfo: KotlinParameterInfo? = receiver - set(value: KotlinParameterInfo?) { + set(value) { if (value != null && value !in newParameters) { newParameters.add(value) } @@ -188,7 +187,7 @@ open class KotlinChangeInfo( private set var primaryPropagationTargets: Collection = emptyList() - set(value: Collection) { + set(value) { field = value val result = LinkedHashSet() @@ -210,7 +209,7 @@ open class KotlinChangeInfo( for (caller in value) { add(caller) - OverridingMethodsSearch.search(caller.getRepresentativeLightMethod() ?: continue).forEach { add(it); true } + OverridingMethodsSearch.search(caller.getRepresentativeLightMethod() ?: continue).forEach { add(it) } } propagationTargetUsageInfos = result.toList() @@ -458,14 +457,14 @@ open class KotlinChangeInfo( currentPsiMethod: PsiMethod, isGetter: Boolean ): JavaChangeInfo? { - val newParameterList = receiverParameterInfo.singletonOrEmptyList() + getNonReceiverParameters() + val newParameterList = listOfNotNull(receiverParameterInfo) + getNonReceiverParameters() val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, newParameterList).toTypedArray() val newName = if (isGetter) JvmAbi.getterName(newName) else newName return createJavaChangeInfo(originalPsiMethod, currentPsiMethod, newName, currentPsiMethod.returnType, newJavaParameters) } fun createJavaChangeInfoForSetter(originalPsiMethod: PsiMethod, currentPsiMethod: PsiMethod): JavaChangeInfo? { - val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, receiverParameterInfo.singletonOrEmptyList()) + val newJavaParameters = getJavaParameterInfos(originalPsiMethod, currentPsiMethod, listOfNotNull(receiverParameterInfo)) val oldIndex = if (methodDescriptor.receiver != null) 1 else 0 if (isPrimaryMethodUpdated) { val newIndex = if (receiverParameterInfo != null) 1 else 0 diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt index f886ee639be..b7ad0775095 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt @@ -71,7 +71,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { @@ -542,7 +541,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val conflictElement = DescriptorToSourceUtils.descriptorToDeclaration(conflict) if (conflictElement === info.method) continue - val candidateTypes = conflict.extensionReceiverParameter?.type.singletonOrEmptyList() + conflict.valueParameters.map { it.type } + val candidateTypes = listOfNotNull(conflict.extensionReceiverParameter?.type) + conflict.valueParameters.map { it.type } if (candidateTypes == newTypes) { result.putValue(conflictElement, "Function already exists: '" + DescriptorRenderer.SHORT_NAMES_IN_TYPES.render(conflict) + "'") diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt index f37b12baf7a..fa0b6fa7e8c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt @@ -446,7 +446,7 @@ class KotlinChangeSignatureDialog( val typeRef = getContentElement() val type = typeRef?.analyze(BodyResolveMode.PARTIAL)?.get(BindingContext.TYPE, typeRef) return when { - type != null && !type.isError -> KotlinTypeInfo(isCovariant, type, if (forPreview) typeRef?.text else null) + type != null && !type.isError -> KotlinTypeInfo(isCovariant, type, if (forPreview) typeRef.text else null) typeRef != null -> KotlinTypeInfo(isCovariant, null, typeRef.text) else -> KotlinTypeInfo(isCovariant) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineValHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineValHandler.kt index 68b343ac0d4..86a00c2a152 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineValHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineValHandler.kt @@ -54,7 +54,6 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import org.jetbrains.kotlin.utils.sure import java.util.* @@ -79,7 +78,7 @@ class KotlinInlineValHandler : InlineActionHandler() { parent.parent.firstChild.text == replacement.firstChild.text) { val entriesToAdd = replacement.entries val templateExpression = parent.parent as KtStringTemplateExpression - val inlinedExpressions = if (entriesToAdd.size > 0) { + val inlinedExpressions = if (entriesToAdd.isNotEmpty()) { val firstAddedEntry = templateExpression.addRangeBefore(entriesToAdd.first(), entriesToAdd.last(), parent) val lastNewEntry = parent.prevSibling val nextElement = parent.nextSibling @@ -99,7 +98,7 @@ class KotlinInlineValHandler : InlineActionHandler() { return inlinedExpressions } - return expression.replaced(replacement).singletonList() + return listOf(expression.replaced(replacement)) } override fun inlineElement(project: Project, editor: Editor?, element: PsiElement) { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractInterfaceDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractInterfaceDialog.kt index 20ef61f6b83..51e94996f75 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractInterfaceDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractClass/ui/KotlinExtractInterfaceDialog.kt @@ -124,5 +124,5 @@ class KotlinExtractInterfaceDialog( override fun getHelpId() = HelpID.EXTRACT_INTERFACE - override fun createExtractedSuperNameField() = super.createExtractedSuperNameField()!!.apply { text = "I${originalClass.name}" } + override fun createExtractedSuperNameField() = super.createExtractedSuperNameField().apply { text = "I${originalClass.name}" } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt index a29b042dea5..5a7f73f1f71 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionData.kt @@ -244,7 +244,7 @@ data class ExtractionData( val invokeDeclaration = getDeclaration(invokeDescriptor, context) ?: synthesizedInvokeDeclaration val variableResolveResult = originalResolveResult.copy(resolvedCall = originalVariableCall!!, descriptor = originalVariableCall.resultingDescriptor) - val functionResolveResult = originalResolveResult.copy(resolvedCall = originalFunctionCall!!, + val functionResolveResult = originalResolveResult.copy(resolvedCall = originalFunctionCall, descriptor = originalFunctionCall.resultingDescriptor, declaration = invokeDeclaration) referencesInfo.add(ResolvedReferenceInfo(newRef, variableResolveResult, smartCast, possibleTypes, shouldSkipPrimaryReceiver)) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt index 1b45220b522..0526a4a4fe8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt @@ -42,7 +42,6 @@ import org.jetbrains.kotlin.psi.psiUtil.getValueParameters import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.supertypes -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.awt.Color import java.util.* import javax.swing.JCheckBox @@ -261,7 +260,7 @@ class KotlinInplaceParameterIntroducer( val originalRange = expr.toRange() return descriptor.copy( originalRange = originalRange, - occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else originalRange.singletonList(), + occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange), argumentValue = expr!! ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt index 4babcdec432..4de97a64277 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt @@ -187,7 +187,7 @@ fun selectNewParameterContext( file = file, title = "Introduce parameter to declaration", elementKinds = listOf(CodeInsightUtils.ElementKind.EXPRESSION), - getContainers = { elements, parent -> + getContainers = { _, parent -> val parents = parent.parents val stopAt = (parent.parents.zip(parent.parents.drop(1))) .firstOrNull { isObjectOrNonInnerClass(it.first) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinIntroducePropertyHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinIntroducePropertyHandler.kt index 729c77ab9a9..54d388e1499 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinIntroducePropertyHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinIntroducePropertyHandler.kt @@ -73,7 +73,7 @@ class KotlinIntroducePropertyHandler( file, "Select target code block", listOf(CodeInsightUtils.ElementKind.EXPRESSION), - { elements, parent -> + { _, parent -> parent.getExtractionContainers(strict = true, includeAll = true).filter { it is KtClassBody || (it is KtFile && !it.isScript) } }, continuation diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt index 9798751e0f9..96775e1b2ce 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt @@ -55,7 +55,7 @@ open class KotlinIntroduceTypeAliasHandler : RefactoringActionHandler { file, "Select target code block", listOf(TYPE_ELEMENT, TYPE_CONSTRUCTOR), - { elements, parent -> listOf(parent.containingFile) }, + { _, parent -> listOf(parent.containingFile) }, continuation ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt index f2750b105ea..6aaa2698915 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt @@ -74,7 +74,7 @@ object KotlinIntroduceTypeParameterHandler : RefactoringActionHandler { file, "Introduce type parameter to declaration", listOf(CodeInsightUtils.ElementKind.TYPE_ELEMENT), - { elements, parent -> getPossibleTypeParameterContainers(parent) }, + { _, parent -> getPossibleTypeParameterContainers(parent) }, continuation ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt index 0831f23b370..e2285a06b04 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt @@ -69,7 +69,6 @@ import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import org.jetbrains.kotlin.utils.ifEmpty import org.jetbrains.kotlin.utils.sure import java.util.* @@ -562,11 +561,11 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { componentFunctions.map { suggestNamesForComponent(it, project, collectingValidator) } } else { - KotlinNameSuggester.suggestNamesByExpressionAndType(expression, - substringInfo?.type, - bindingContext, - validator, - "value").singletonList() + listOf(KotlinNameSuggester.suggestNamesByExpressionAndType(expression, + substringInfo?.type, + bindingContext, + validator, + "value")) } val introduceVariableContext = IntroduceVariableContext( diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt index a1c3e0ee2e8..2a7e5bc6740 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt @@ -38,7 +38,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.util.isValidOperator -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* private fun getApplicableComponentFunctions( @@ -54,7 +53,7 @@ private fun getApplicableComponentFunctions( PrimitiveType.values().mapTo(forbiddenClasses) { builtIns.getPrimitiveArrayClassDescriptor(it) } (receiverType ?: context.getType(contextExpression))?.let { - if ((it.singletonList() + it.supertypes()).any { + if ((listOf(it) + it.supertypes()).any { val fqName = it.constructor.declarationDescriptor?.importableFqName forbiddenClasses.any { it.fqNameSafe == fqName } }) return emptyList() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/kotlinRefactoringUtil.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/kotlinRefactoringUtil.kt index 30df88c435e..d846521c2b1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/kotlinRefactoringUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/kotlinRefactoringUtil.kt @@ -253,7 +253,7 @@ fun getPsiElementPopup( val list = JBList(elements.map(toPsi)) list.cellRenderer = renderer - list.addListSelectionListener { e -> + list.addListSelectionListener { highlighter?.dropHighlight() val index = list.selectedIndex if (index >= 0) { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt index 564b62bdb9d..e87838cf5a6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt @@ -171,7 +171,7 @@ class MoveKotlinDeclarationsProcessor( val usages = ArrayList() val conflictChecker = MoveConflictChecker(project, elementsToMove, descriptor.moveTarget, elementsToMove.first()) - for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { + for (kotlinToLightElements in kotlinToLightElementsBySourceFile.values) { kotlinToLightElements.keys.forEach { if (descriptor.updateInternalReferences) { val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget) @@ -201,10 +201,10 @@ class MoveKotlinDeclarationsProcessor( override fun performRefactoring(usages: Array) { fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration? { val file = declaration.containingFile as? KtFile - assert(file != null) { "${declaration.javaClass}: ${declaration.text}" } + assert(file != null) { "${declaration::class.java}: ${declaration.text}" } val targetContainer = moveTarget.getOrCreateTargetPsi(declaration) - ?: throw AssertionError("Couldn't create Kotlin file for: ${declaration.javaClass}: ${declaration.text}") + ?: throw AssertionError("Couldn't create Kotlin file for: ${declaration::class.java}: ${declaration.text}") descriptor.delegate.preprocessDeclaration(descriptor, declaration) val newElement = mover(declaration, targetContainer) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt index dffd503eec7..e06e57d2039 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt @@ -135,7 +135,7 @@ class KotlinPullUpDialog( private val sourceClass: KtClassOrObject get() = myClass as KtClassOrObject - override fun getDimensionServiceKey() = "#" + javaClass.name + override fun getDimensionServiceKey() = "#" + this::class.java.name override fun getSuperClass() = super.getSuperClass() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt index 88ab55779d6..559d216985b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt @@ -551,7 +551,7 @@ class KotlinPullUpHelper( fun KtClassOrObject.getOrCreateClassInitializer(): KtAnonymousInitializer { getOrCreateBody().declarations.lastOrNull { it is KtAnonymousInitializer }?.let { return it as KtAnonymousInitializer } - return addDeclaration(psiFactory.createAnonymousInitializer()) as KtAnonymousInitializer + return addDeclaration(psiFactory.createAnonymousInitializer()) } fun KtElement.getConstructorBodyBlock(): KtBlockExpression? { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt index 151b06d82f0..d6e5b7873ea 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt @@ -68,7 +68,7 @@ fun addMemberToTarget(targetMember: KtNamedDeclaration, targetClass: KtClassOrOb return parameterList.addParameterBefore(targetMember, anchor) } - val anchor = targetClass.declarations.filterIsInstance(targetMember.javaClass).lastOrNull() + val anchor = targetClass.declarations.filterIsInstance(targetMember::class.java).lastOrNull() val movedMember = when { anchor == null && targetMember is KtProperty -> targetClass.addDeclarationBefore(targetMember, null) else -> targetClass.addDeclarationAfter(targetMember, anchor) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt index 8dfb7d5fa8e..2c2405558e6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt @@ -54,7 +54,7 @@ class KotlinPushDownDialog( val selectedMemberInfos: List get() = memberInfos.filter { it.isChecked && memberInfoModel?.isMemberEnabled(it) ?: false } - override fun getDimensionServiceKey() = "#" + javaClass.name + override fun getDimensionServiceKey() = "#" + this::class.java.name override fun createNorthPanel(): JComponent? { val gbConstraints = GridBagConstraints() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassProcessor.kt index 682f2b28781..04d36e7c85f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassProcessor.kt @@ -127,7 +127,7 @@ class RenameKotlinClassProcessor : RenameKotlinPsiProcessor() { when (element) { is KtLightClassForSourceDeclaration -> element.kotlinOrigin is KtLightClassForFacade -> element - else -> throw AssertionError("Should not be suggested to rename element of type " + element.javaClass + " " + element) + else -> throw AssertionError("Should not be suggested to rename element of type " + element::class.java + " " + element) } is KtConstructor<*> -> diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt index 88408649515..73859f43f2b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt @@ -64,7 +64,6 @@ import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.util.findCallableMemberBySignature import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.SmartList -import org.jetbrains.kotlin.utils.singletonOrEmptyList class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { override fun canProcessElement(element: PsiElement): Boolean { @@ -279,7 +278,7 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { return preprocessAndPass(callableDeclaration) } - val superPsiMethods = deepestSuperDeclaration.getRepresentativeLightMethod().singletonOrEmptyList() + val superPsiMethods = listOfNotNull(deepestSuperDeclaration.getRepresentativeLightMethod()) checkSuperMethodsWithPopup(callableDeclaration, superPsiMethods, "Rename", editor) { preprocessAndPass(if (it.size > 1) deepestSuperDeclaration else callableDeclaration) } @@ -445,7 +444,6 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } } } - true } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt index 80992ac93ff..c96783cbac5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt @@ -59,7 +59,6 @@ import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.utils.SmartList -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.util.* internal fun ResolvedCall<*>.noReceivers() = dispatchReceiver == null && extensionReceiver == null @@ -166,7 +165,7 @@ private fun LexicalScope.getRelevantDescriptors( val nameAsName = Name.identifier(name) return when (declaration) { is KtProperty, is KtParameter, is PsiField -> getAllAccessibleVariables(nameAsName) - is KtClassOrObject, is PsiClass -> findClassifier(nameAsName, NoLookupLocation.FROM_IDE).singletonOrEmptyList() + is KtClassOrObject, is PsiClass -> listOfNotNull(findClassifier(nameAsName, NoLookupLocation.FROM_IDE)) else -> emptyList() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt index bb51dc4847b..c4f6d0c7c71 100644 --- a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt @@ -48,7 +48,6 @@ import org.jetbrains.kotlin.idea.util.runWithAlternativeResolveEnabled import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset -import org.jetbrains.kotlin.utils.addToStdlib.singletonList import java.util.* class KotlinCreateTestIntention : SelfTargetingRangeIntention(KtNamedDeclaration::class.java, "Create test") { @@ -186,7 +185,7 @@ class KotlinCreateTestIntention : SelfTargetingRangeIntention + val extraFiles = rootDir.listFiles { _, name -> if (!name.startsWith(prefix) || name == mainFileName) return@listFiles false val ext = FileUtilRt.getExtension(name) diff --git a/idea/tests/org/jetbrains/kotlin/idea/RegisteredFindersTest.kt b/idea/tests/org/jetbrains/kotlin/idea/RegisteredFindersTest.kt index edd11bd5bd8..813d350437f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/RegisteredFindersTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/RegisteredFindersTest.kt @@ -32,7 +32,7 @@ class RegisteredFindersTest : KotlinLightCodeInsightFixtureTestCase() { project.getExtensions(PsiElementFinder.EP_NAME).forEach { finder -> if (finder is NonClasspathClassFinder) { - val name = finder.javaClass.simpleName + val name = finder::class.java.simpleName val removed = expectedFindersNames.remove(name) Assert.assertTrue("Unknown finder found: $finder, class name: $name, search in $expectedFindersNames.\n" + "Consider updating ${KotlinJavaPsiFacade::class.java}", diff --git a/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt index 78ba636619c..f9501232612 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt @@ -56,7 +56,7 @@ abstract class AbstractNavigationTest : KotlinLightCodeInsightFixtureTestCase() val mainFileBaseName = mainFileName.substring(0, mainFileName.indexOf('.')) configureExtra(mainFileBaseName, fileText) mainFile.parentFile - .listFiles { file, name -> + .listFiles { _, name -> name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java") || name.endsWith(".xml")) } .forEach{ myFixture.configureByFile(it.name) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt index dd131866597..3526c5c1de8 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt @@ -52,7 +52,7 @@ abstract class AbstractIdeCompiledLightClassTest : KotlinDaemonAnalyzerTestCase( val testName = getTestName(false) if (KotlinTestUtils.isAllFilesPresentTest(testName)) return - val filePath = "${KotlinTestUtils.getTestsRoot(this.javaClass)}/${getTestName(false)}.kt" + val filePath = "${KotlinTestUtils.getTestsRoot(this::class.java)}/${getTestName(false)}.kt" Assert.assertTrue("File doesn't exist $filePath", File(filePath).exists()) diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt index aa034e87aef..a6178825b0f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt @@ -88,7 +88,7 @@ object PsiElementChecker { acceptChildren(PsiElementVisitor.EMPTY_VISITOR) val copy = copy() - Assert.assertTrue(copy == null || copy.javaClass == this.javaClass) + Assert.assertTrue(copy == null || copy::class.java == this::class.java) // Modify methods: // add(this) @@ -123,7 +123,7 @@ object PsiElementChecker { Assert.assertTrue(isEquivalentTo(this)) } catch (t: Throwable) { - throw AssertionErrorWithCause("Failed for ${this.javaClass} ${this}", t) + throw AssertionErrorWithCause("Failed for ${this::class.java} ${this}", t) } } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt index 38901420880..5c91d5c2a15 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt @@ -50,7 +50,7 @@ abstract class AbstractMultiFileInspectionTest : KotlinMultiFileTestCase() { val withFullJdk = config["withFullJdk"]?.asBoolean ?: false - doTest({ rootDir, rootAfter -> + doTest({ _, _ -> try { if (withRuntime) { ConfigLibraryUtil.configureKotlinRuntimeAndSdk( diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt index 70e20d658c5..8c0d8e80999 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt @@ -67,7 +67,7 @@ abstract class AbstractCodeInsightActionTest : KotlinLightCodeInsightFixtureTest val fileNameBase = mainFile.nameWithoutExtension + "." val rootDir = mainFile.parentFile rootDir - .list { file, name -> + .list { _, name -> name.startsWith(fileNameBase) && name != mainFileName && (name.endsWith(".kt") || name.endsWith(".java")) } .forEach { diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt index 2ed069da3fe..8ca8a79aa7b 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt @@ -54,7 +54,7 @@ abstract class AbstractMoveStatementTest : AbstractCodeMoverTest() { it.checkAvailable(LightPlatformCodeInsightTestCase.getEditor(), LightPlatformCodeInsightTestCase.getFile(), info, direction == "down") } ?: error("No mover found") - assertEquals("Unmatched movers", defaultMoverClass.name, actualMover.javaClass.name) + assertEquals("Unmatched movers", defaultMoverClass.name, actualMover::class.java.name) assertEquals("Invalid applicability", isApplicableExpected, info.toMove2 != null) } } @@ -62,7 +62,7 @@ abstract class AbstractMoveStatementTest : AbstractCodeMoverTest() { abstract class AbstractMoveLeftRightTest : AbstractCodeMoverTest() { protected fun doTest(path: String) { - doTest(path) { isApplicableExpected, direction -> } + doTest(path) { _, _ -> } } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerTestBase.kt b/idea/tests/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerTestBase.kt index 6a97ed7c607..17a4f85ee96 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerTestBase.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerTestBase.kt @@ -296,7 +296,7 @@ abstract class KotlinDebuggerTestBase : KotlinDebuggerTestCase() { } } else if (comment.startsWith("//Breakpoint!")) { - val ordinal = getPropertyFromComment(comment, "lambdaOrdinal")?.toInt() ?: null + val ordinal = getPropertyFromComment(comment, "lambdaOrdinal")?.toInt() val condition = getPropertyFromComment(comment, "condition") createLineBreakpoint(breakpointManager, file, lineIndex, ordinal, condition) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt index 1175c81aef0..75e27e4cc39 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt @@ -32,10 +32,10 @@ abstract class AbstractInternalCompiledClassesTest : KotlinLightCodeInsightFixtu } protected fun isSyntheticClass(): VirtualFile.() -> Boolean = - isFileWithHeader { header, classId -> header.kind == KotlinClassHeader.Kind.SYNTHETIC_CLASS } + isFileWithHeader { header, _ -> header.kind == KotlinClassHeader.Kind.SYNTHETIC_CLASS } protected fun doTestNoPsiFilesAreBuiltForLocalClass(): Unit = - doTestNoPsiFilesAreBuiltFor("local", isFileWithHeader { header, classId -> classId.isLocal }) + doTestNoPsiFilesAreBuiltFor("local", isFileWithHeader { _, classId -> classId.isLocal }) protected fun doTestNoPsiFilesAreBuiltForSyntheticClasses(): Unit = doTestNoPsiFilesAreBuiltFor("synthetic", isSyntheticClass()) diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt index 6c336c2ffcf..9a62844bab8 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt @@ -83,7 +83,7 @@ class NavigateFromLibrarySourcesTest: LightCodeInsightFixtureTestCase() { assertEquals(expectedFqName, element.fqName!!.asString()) } else -> { - fail("Navigation element should be JetClass or PsiClass: " + element.javaClass + ", " + element.text) + fail("Navigation element should be JetClass or PsiClass: " + element::class.java + ", " + element.text) } } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextFromJsMetadataTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextFromJsMetadataTest.kt index 66ea9192f03..c4b6472e307 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextFromJsMetadataTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextFromJsMetadataTest.kt @@ -31,7 +31,7 @@ abstract class AbstractDecompiledTextFromJsMetadataTest(baseDirectory: String) : override fun getFileToDecompile(): VirtualFile = getKjsmFile(TEST_PACKAGE, myModule!!) override fun checkPsiFile(psiFile: PsiFile) = - assertTrue(psiFile is KtDecompiledFile, "Expecting decompiled kotlin javascript file, was: " + psiFile.javaClass) + assertTrue(psiFile is KtDecompiledFile, "Expecting decompiled kotlin javascript file, was: " + psiFile::class.java) override fun setUp() { super.setUp() diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt index 9c7abcb8311..7535823d569 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt @@ -30,7 +30,7 @@ abstract class AbstractDecompiledTextTest(baseDirectory: String, allowKotlinPack override fun getFileToDecompile(): VirtualFile = getClassFile(TEST_PACKAGE, getTestName(false), myModule!!) override fun checkPsiFile(psiFile: PsiFile) = - assertTrue(psiFile is KtClsFile, "Expecting decompiled kotlin file, was: " + psiFile.javaClass) + assertTrue(psiFile is KtClsFile, "Expecting decompiled kotlin file, was: " + psiFile::class.java) } abstract class AbstractCommonDecompiledTextTest : AbstractDecompiledTextTest("/decompiler/decompiledText", true) diff --git a/idea/tests/org/jetbrains/kotlin/idea/folding/FoldingAfterOptimizeImportsTest.kt b/idea/tests/org/jetbrains/kotlin/idea/folding/FoldingAfterOptimizeImportsTest.kt index a4f1ac1e761..6b4ee8ca227 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/folding/FoldingAfterOptimizeImportsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/folding/FoldingAfterOptimizeImportsTest.kt @@ -47,7 +47,6 @@ class FoldingAfterOptimizeImportsTest : AbstractKotlinFoldingTest() { fixture.configureByFile(getTestName(true) + ".kt") doTestWithSettings(fileText) { - fileText -> CodeFoldingManager.getInstance(fixture.project)!!.buildInitialFoldings(editor) getFoldingRegion(0).checkRegion(false, findStringWithPrefixes("// REGION BEFORE: ")) diff --git a/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt index ffeb6af9143..9d58ef09263 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt @@ -97,7 +97,7 @@ class InspectionDescriptionTest : LightPlatformTestCase() { val toolWrappers = loadKotlinInspections() val errors = StringBuilder() toolWrappers.filter({ toolWrapper -> toolWrapper.extension == null }).forEach { toolWrapper -> - errors.append("Please add XML mapping for ").append(toolWrapper.tool.javaClass) + errors.append("Please add XML mapping for ").append(toolWrapper.tool::class.java) } UsefulTestCase.assertEmpty(errors.toString()) diff --git a/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt index 3195d813acb..f583679fe2a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt @@ -49,7 +49,7 @@ abstract class AbstractMultiFileIntentionTest : KotlinMultiFileTestCase() { ConfigLibraryUtil.configureKotlinRuntimeAndSdk(myModule, PluginTestCaseBase.mockJdk()) } - doTest({ rootDir, rootAfter -> + doTest({ rootDir, _ -> val mainFile = rootDir.findFileByRelativePath(mainFilePath)!! val conflictFile = rootDir.findFileByRelativePath("$mainFilePath.conflicts") val document = FileDocumentManager.getInstance().getDocument(mainFile)!! @@ -58,7 +58,7 @@ abstract class AbstractMultiFileIntentionTest : KotlinMultiFileTestCase() { val mainPsiFile = PsiManager.getInstance(project!!).findFile(mainFile)!! try { - Assert.assertTrue("isAvailable() for ${intentionAction.javaClass} should return $isApplicableExpected", + Assert.assertTrue("isAvailable() for ${intentionAction::class.java} should return $isApplicableExpected", isApplicableExpected == intentionAction.isAvailable(project, editor, mainPsiFile)) config.getNullableString("intentionText")?.let { TestCase.assertEquals("Intention text mismatch", it, intentionAction.text) diff --git a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt index 8a03c0e7991..6479cf500d5 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt @@ -36,7 +36,7 @@ import org.junit.Assert abstract class AbstractParameterInfoTest : LightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor { - val root = KotlinTestUtils.getTestsRoot(this.javaClass) + val root = KotlinTestUtils.getTestsRoot(this::class.java) if (root.contains("Lib")) { return JdkAndMockLibraryProjectDescriptor( "$root/sharedLib", true, true, false, false diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt index 7b54c4764eb..3eec7864f08 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt @@ -52,7 +52,7 @@ abstract class AbstractMemberPullPushTest : KotlinLightCodeInsightFixtureTestCas val mainFileName = mainFile.name val mainFileBaseName = FileUtil.getNameWithoutExtension(mainFileName) - val extraFiles = mainFile.parentFile.listFiles { file, name -> + val extraFiles = mainFile.parentFile.listFiles { _, name -> name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java")) } val extraFilesToPsi = extraFiles.associateBy { fixture.configureByFile(it.name) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt index 6b99074d813..d532e321fd6 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt @@ -43,7 +43,7 @@ abstract class AbstractInlineTest : KotlinLightCodeInsightFixtureTestCase() { val mainFileName = mainFile.name val mainFileBaseName = FileUtil.getNameWithoutExtension(mainFileName) - val extraFiles = mainFile.parentFile.listFiles { file, name -> + val extraFiles = mainFile.parentFile.listFiles { _, name -> name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java")) } val extraFilesToPsi = extraFiles.associateBy { fixture.configureByFile(path.replace(mainFileName, it.name)) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt index d76a47d8dcc..8c139219ad1 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt @@ -69,13 +69,12 @@ import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.util.findElementByCommentPrefix -import org.jetbrains.kotlin.utils.emptyOrSingletonList import java.io.File import java.lang.AssertionError import java.util.* import kotlin.test.assertEquals -abstract class AbstractExtractionTest() : KotlinLightCodeInsightFixtureTestCase() { +abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = LightCodeInsightFixtureTestCase.JAVA_LATEST val fixture: JavaCodeInsightTestFixture get() = myFixture @@ -125,12 +124,12 @@ abstract class AbstractExtractionTest() : KotlinLightCodeInsightFixtureTestCase( with (handler) { val target = (file as KtFile).findElementByCommentPrefix("// TARGET:") as? KtNamedDeclaration if (target != null) { - selectElement(fixture.getEditor(), file, true, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) { element -> - invoke(fixture.getProject(), fixture.getEditor(), element as KtExpression, target) + selectElement(fixture.editor, file, true, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) { element -> + invoke(fixture.project, fixture.editor, element as KtExpression, target) } } else { - invoke(fixture.getProject(), fixture.getEditor(), file, null) + invoke(fixture.project, fixture.editor, file, null) } } } @@ -293,7 +292,7 @@ abstract class AbstractExtractionTest() : KotlinLightCodeInsightFixtureTestCase( val actualReturnTypes = descriptor.controlFlow.possibleReturnTypes.map { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } - val allParameters = emptyOrSingletonList(descriptor.receiverParameter) + descriptor.parameters + val allParameters = listOfNotNull(descriptor.receiverParameter) + descriptor.parameters val actualDescriptors = allParameters.map { renderer.render(it.originalDescriptor) }.joinToString() val actualTypes = allParameters.map { it.getParameterTypeCandidates(false).map { renderer.renderType(it) }.joinToString(", ", "[", "]") @@ -405,7 +404,7 @@ abstract class AbstractExtractionTest() : KotlinLightCodeInsightFixtureTestCase( val mainFileName = mainFile.name val mainFileBaseName = FileUtil.getNameWithoutExtension(mainFileName) - val extraFiles = mainFile.parentFile.listFiles { file, name -> + val extraFiles = mainFile.parentFile.listFiles { _, name -> name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java")) } val extraFilesToPsi = extraFiles.associateBy { fixture.configureByFile(it.name) } @@ -436,7 +435,7 @@ abstract class AbstractExtractionTest() : KotlinLightCodeInsightFixtureTestCase( KotlinTestUtils.assertEqualsToFile(conflictFile, e.message!!) } catch(e: RuntimeException) { // RuntimeException is thrown by IDEA code in CodeInsightUtils.java - if (e.javaClass != RuntimeException::class.java) throw e + if (e::class.java != RuntimeException::class.java) throw e KotlinTestUtils.assertEqualsToFile(conflictFile, e.message!!) } finally { diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt index 5ea39264828..bad2a9b41a3 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt @@ -75,7 +75,7 @@ abstract class AbstractMoveTest : KotlinMultiFileTestCase() { } isMultiModule = config["isMultiModule"]?.asBoolean ?: false - doTest({ rootDir, rootAfter -> + doTest({ rootDir, _ -> val mainFile = rootDir.findFileByRelativePath(mainFilePath)!! val mainPsiFile = PsiManager.getInstance(project!!).findFile(mainFile)!! val document = FileDocumentManager.getInstance().getDocument(mainFile)!! diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt index c2dbe8be05d..a299ddeb074 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt @@ -40,8 +40,8 @@ abstract class AbstractPushDownTest : AbstractMemberPullPushTest() { } protected fun doJavaTest(path: String) { - doTest(path) { file -> - val elementAt = getFile().findElementAt(editor.caretModel.offset) + doTest(path) { + val elementAt = file.findElementAt(editor.caretModel.offset) val sourceClass = PsiTreeUtil.getParentOfType(elementAt, PsiClass::class.java)!! val storage = MemberInfoStorage(sourceClass) { true } val memberInfos = chooseMembers(storage.getClassMemberInfos(sourceClass)) diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt index 1258f912567..7d7c16cf9e6 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt @@ -168,7 +168,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val mainFilePath = renameParamsObject.getString("mainFile") val newName = renameParamsObject.getString("newName") - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { rootDir, _ -> configExtra(rootDir, renameParamsObject) val mainFile = rootDir.findFileByRelativePath(mainFilePath)!! @@ -209,7 +209,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val classFQN = renameParamsObject.getString("classId").toClassId().asSingleFqName().asString() val newName = renameParamsObject.getString("newName") - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { _, _ -> val aClass = context.javaFacade.findClass(classFQN, context.project.allScope())!! val substitution = RenamePsiElementProcessor.forElement(aClass).substituteElementToRename(aClass, null) @@ -222,7 +222,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val methodSignature = renameParamsObject.getString("methodSignature") val newName = renameParamsObject.getString("newName") - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { _, _ -> val aClass = context.javaFacade.findClass(classFQN, GlobalSearchScope.moduleScope(context.module))!! val methodText = context.javaFacade.elementFactory.createMethodFromText(methodSignature + "{}", null) @@ -239,20 +239,20 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val oldMethodName = Name.identifier(renameParamsObject.getString("oldName")) doRenameInKotlinClassOrPackage(renameParamsObject, context) { - declaration, scope -> scope.getContributedFunctions(oldMethodName, NoLookupLocation.FROM_TEST).first() } + _, scope -> scope.getContributedFunctions(oldMethodName, NoLookupLocation.FROM_TEST).first() } } private fun renameKotlinPropertyTest(renameParamsObject: JsonObject, context: TestContext) { val oldPropertyName = Name.identifier(renameParamsObject.getString("oldName")) doRenameInKotlinClassOrPackage(renameParamsObject, context) { - declaration, scope -> scope.getContributedVariables(oldPropertyName, NoLookupLocation.FROM_TEST).first() } + _, scope -> scope.getContributedVariables(oldPropertyName, NoLookupLocation.FROM_TEST).first() } } private fun renameKotlinClassTest(renameParamsObject: JsonObject, context: TestContext) { renameParamsObject.getString("classId") //assertion - doRenameInKotlinClassOrPackage(renameParamsObject, context) { declaration, scope -> declaration as ClassDescriptor } + doRenameInKotlinClassOrPackage(renameParamsObject, context) { declaration, _ -> declaration as ClassDescriptor } } private fun renameKotlinPackageTest(renameParamsObject: JsonObject, context: TestContext) { @@ -260,7 +260,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val newName = renameParamsObject.getString("newName") val mainFilePath = renameParamsObject.getNullableString("mainFile") ?: "${getTestDirName(false)}.kt" - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { rootDir, _ -> val mainFile = rootDir.findChild(mainFilePath)!! val document = FileDocumentManager.getInstance().getDocument(mainFile)!! val jetFile = PsiDocumentManager.getInstance(context.project).getPsiFile(document) as KtFile @@ -282,7 +282,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val file = renameParamsObject.getString("file") val newName = renameParamsObject.getString("newName") - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { rootDir, _ -> val mainFile = rootDir.findFileByRelativePath(file)!! val psiFile = PsiManager.getInstance(context.project).findFile(mainFile) @@ -295,7 +295,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val oldName = renameParamsObject.getString("oldName") val newName = renameParamsObject.getString("newName") - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { rootDir, _ -> val mainFile = rootDir.findChild(file)!! val psiFile = PsiManager.getInstance(context.project).findFile(mainFile) as PropertiesFile val property = psiFile.findPropertyByKey(oldName) as Property @@ -319,7 +319,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val newName = renameParamsObject.getString("newName") val mainFilePath = renameParamsObject.getNullableString("mainFile") ?: "${getTestDirName(false)}.kt" - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { rootDir, _ -> val mainFile = rootDir.findChild(mainFilePath)!! val document = FileDocumentManager.getInstance().getDocument(mainFile)!! val jetFile = PsiDocumentManager.getInstance(context.project).getPsiFile(document) as KtFile @@ -344,7 +344,7 @@ abstract class AbstractRenameTest : KotlinMultiFileTestCase() { val mainFilePath = renameParamsObject.getString("mainFile") val newName = renameParamsObject.getString("newName") - doTestCommittingDocuments { rootDir, rootAfter -> + doTestCommittingDocuments { rootDir, _ -> configExtra(rootDir, renameParamsObject) val psiFile = rootDir.findFileByRelativePath(mainFilePath)!!.toPsiFile(project)!! diff --git a/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInJavaTest.kt b/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInJavaTest.kt index 0b393d3fa26..4ff1aa3f064 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInJavaTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInJavaTest.kt @@ -48,7 +48,7 @@ abstract class AbstractReferenceToCompiledKotlinResolveInJavaTest : AbstractRefe override fun checkResolvedTo(element: PsiElement) { val navigationElement = element.navigationElement - Assert.assertFalse("Reference should not navigate to a light element\nWas: ${navigationElement.javaClass.simpleName}", navigationElement is KtLightElement<*, *>) - Assert.assertTrue("Reference should navigate to a kotlin declaration\nWas: ${navigationElement.javaClass.simpleName}", navigationElement is KtDeclaration || navigationElement is KtClsFile) + Assert.assertFalse("Reference should not navigate to a light element\nWas: ${navigationElement::class.java.simpleName}", navigationElement is KtLightElement<*, *>) + Assert.assertTrue("Reference should navigate to a kotlin declaration\nWas: ${navigationElement::class.java.simpleName}", navigationElement is KtDeclaration || navigationElement is KtClsFile) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt b/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt index 5a678f9f943..ee118ebff98 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt @@ -208,7 +208,7 @@ class DebugTextByStubTest : LightCodeInsightFixtureTestCase() { fun testPropertyAccessors() { val tree = createStubTree("var c: Int\nget() = 3\nset(i: Int) {}") val propertyStub = tree.findChildStubByType(KtStubElementTypes.PROPERTY)!! - val accessors = propertyStub.getChildrenByType(KtStubElementTypes.PROPERTY_ACCESSOR, KtStubElementTypes.PROPERTY_ACCESSOR.arrayFactory)!! + val accessors = propertyStub.getChildrenByType(KtStubElementTypes.PROPERTY_ACCESSOR, KtStubElementTypes.PROPERTY_ACCESSOR.arrayFactory) assertEquals("getter for STUB: var c: Int", accessors[0].getDebugText()) assertEquals("setter for STUB: var c: Int", accessors[1].getDebugText()) } @@ -216,7 +216,7 @@ class DebugTextByStubTest : LightCodeInsightFixtureTestCase() { fun testEnumEntry() { val tree = createStubTree("enum class Enum { E1, E2(), E3(1, 2)}") val enumClass = tree.findChildStubByType(KtStubElementTypes.CLASS)!!.findChildStubByType(KtStubElementTypes.CLASS_BODY)!! - val entries = enumClass.getChildrenByType(KtStubElementTypes.ENUM_ENTRY, KtStubElementTypes.ENUM_ENTRY.arrayFactory)!! + val entries = enumClass.getChildrenByType(KtStubElementTypes.ENUM_ENTRY, KtStubElementTypes.ENUM_ENTRY.arrayFactory) assertEquals("STUB: enum entry E1", entries[0].getDebugText()) assertEquals("STUB: enum entry E2 : Enum", entries[1].getDebugText()) assertEquals("STUB: enum entry E3 : Enum", entries[2].getDebugText()) diff --git a/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt index b4f041463fe..eeebf82a0c4 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt @@ -205,12 +205,12 @@ class AnnotationConverter(private val converter: Converter) { } is PsiAnnotation -> { - listOf({ codeConverter -> + listOf({ _ -> val (name, arguments) = convertAnnotationValue(value)!! AnnotationConstructorCall(name, arguments).assignPrototype(value) }) } - else -> listOf({ codeConverter -> DummyStringExpression(value?.text ?: "").assignPrototype(value) }) + else -> listOf({ _ -> DummyStringExpression(value?.text ?: "").assignPrototype(value) }) } } @@ -226,7 +226,7 @@ class AnnotationConverter(private val converter: Converter) { if (expectedType is PsiArrayType && !isVararg) { return convertArrayInitializerValue(codeConverter, value.text, - listOf({ codeConverter -> expression }), + listOf({ _ -> expression }), expectedType, false ).assignPrototype(value) diff --git a/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt index 4422a4a490f..b3bbc635c5d 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt @@ -19,7 +19,6 @@ package org.jetbrains.kotlin.j2k import com.intellij.psi.* import com.intellij.psi.CommonClassNames.* import org.jetbrains.kotlin.j2k.ast.* -import org.jetbrains.kotlin.utils.addToStdlib.check class CodeConverter( val converter: Converter, @@ -81,7 +80,7 @@ class CodeConverter( fun convertLocalVariable(variable: PsiLocalVariable): LocalVariable { val isVal = canChangeType(variable) val type = typeConverter.convertVariableType(variable) - val explicitType = type.check { settings.specifyLocalVariableTypeByDefault || converter.shouldDeclareVariableType(variable, type, isVal) } + val explicitType = type.takeIf { settings.specifyLocalVariableTypeByDefault || converter.shouldDeclareVariableType(variable, type, isVal) } return LocalVariable(variable.declarationIdentifier(), converter.convertAnnotations(variable), converter.convertModifiers(variable, false), diff --git a/j2k/src/org/jetbrains/kotlin/j2k/ConstructorConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/ConstructorConverter.kt index 7077130c6e5..fba2cd0acc2 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/ConstructorConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/ConstructorConverter.kt @@ -170,7 +170,7 @@ class ConstructorConverter( } } else { - { it -> Block.Empty } + { Block.Empty } } // we need to replace renamed parameter usages in base class constructor arguments and in default values diff --git a/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt b/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt index 333f4c0e2ba..aaecb801722 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt @@ -33,7 +33,6 @@ import org.jetbrains.kotlin.j2k.usageProcessing.UsageProcessingExpressionConvert import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.types.expressions.OperatorConventions.* -import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList import java.lang.IllegalArgumentException import java.util.* @@ -395,7 +394,7 @@ class Converter private constructor( var setter: PropertyAccessor? = null if (propertyInfo.needExplicitSetter) { - val accessorModifiers = Modifiers(propertyInfo.specialSetterAccess.singletonOrEmptyList()).assignNoPrototype() + val accessorModifiers = Modifiers(listOfNotNull(propertyInfo.specialSetterAccess)).assignNoPrototype() if (setMethod != null && !propertyInfo.isSetMethodBodyFieldAccess) { val method = convertMethod(setMethod, null, null, null, classKind)!! if (method.modifiers.contains(Modifier.EXTERNAL)) @@ -729,6 +728,7 @@ class Converter private constructor( when (nullability) { Nullability.NotNull -> type = type.toNotNullType() Nullability.Nullable -> type = type.toNullableType() + Nullability.Default -> {} } return FunctionParameter(parameter.declarationIdentifier(), type, varValModifier, convertAnnotations(parameter), modifiers, defaultValue).assignPrototype(parameter, CommentsAndSpacesInheritance.LINE_BREAKS) diff --git a/j2k/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt index f0e2cca8765..1bf9c40d23f 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/JavaToKotlinConverter.kt @@ -189,7 +189,7 @@ class JavaToKotlinConverter( private fun processUsages(refs: Collection) { for (fileRefs in refs.groupBy { it.file }.values) { // group by file for faster sorting ReferenceLoop@ - for ((reference, target, file, processings) in fileRefs.sortedWith(ReferenceComparator)) { + for ((reference, _, _, processings) in fileRefs.sortedWith(ReferenceComparator)) { val processors = when (reference.element.language) { JavaLanguage.INSTANCE -> processings.flatMap { it.javaCodeProcessors } KotlinLanguage.INSTANCE -> processings.flatMap { it.kotlinCodeProcessors } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt b/j2k/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt index 2a568b3ecb6..3ba95c312e9 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/SpecialMethod.kt @@ -21,7 +21,6 @@ import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING import com.intellij.psi.impl.PsiExpressionEvaluator import org.jetbrains.kotlin.j2k.ast.* -import org.jetbrains.kotlin.utils.addToStdlib.check import java.io.PrintStream import java.util.* @@ -346,7 +345,7 @@ enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String STRING_GET_BYTES(JAVA_LANG_STRING, "getBytes", null) { override fun ConvertCallData.convertCall(): MethodCallExpression { - val charsetArg = arguments.lastOrNull()?.check { it.type?.canonicalText == JAVA_LANG_STRING } + val charsetArg = arguments.lastOrNull()?.takeIf { it.type?.canonicalText == JAVA_LANG_STRING } val convertedArguments = codeConverter.convertExpressionsInList(arguments).map { if (charsetArg != null && it.prototypes?.singleOrNull()?.element == charsetArg) MethodCallExpression.buildNonNull(null, "charset", ArgumentList.withNoPrototype(it)).assignNoPrototype() @@ -523,7 +522,7 @@ enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String val candidates = valuesByName[method.name] ?: return null return candidates .firstOrNull { it.matches(method, services.superMethodsSearcher) } - ?.check { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct + ?.takeIf { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct } } } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/ast/Parameter.kt b/j2k/src/org/jetbrains/kotlin/j2k/ast/Parameter.kt index d11ff764bec..d5242b72e79 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/ast/Parameter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/ast/Parameter.kt @@ -43,6 +43,7 @@ class FunctionParameter(identifier: Identifier, when (varVal) { VarValModifier.Var -> builder.append("var ") VarValModifier.Val -> builder.append("val ") + VarValModifier.None -> {} } builder.append(identifier) diff --git a/j2k/src/org/jetbrains/kotlin/j2k/importConversion.kt b/j2k/src/org/jetbrains/kotlin/j2k/importConversion.kt index 92cdc6e74b4..cdb79ccd318 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/importConversion.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/importConversion.kt @@ -32,7 +32,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.annotations.hasJvmStaticAnnotation import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform -import org.jetbrains.kotlin.utils.singletonOrEmptyList fun Converter.convertImportList(importList: PsiImportList): ImportList { val imports = importList.allImportStatements @@ -134,7 +133,7 @@ private fun convertStaticExplicitImport(fqName: FqName, target: PsiElement?): Li is KtClassBody -> { val parentClass = originParent.parent as KtClassOrObject if (parentClass is KtObjectDeclaration && parentClass.isCompanion()) { - return parentClass.getFqName()?.child(nameToImport)?.render().singletonOrEmptyList() + return listOfNotNull(parentClass.getFqName()?.child(nameToImport)?.render()) } } } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt b/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt index a72af8b4115..2faac6d725d 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt @@ -28,7 +28,6 @@ import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.utils.addIfNotNull -import org.jetbrains.kotlin.utils.addToStdlib.check import java.util.* class PropertyInfo( @@ -227,7 +226,7 @@ private class PropertyDetector( converter.convertModifiers(field, false).accessModifier() else propertyAccess - val specialSetterAccess = setterAccess?.check { it != propertyAccess } + val specialSetterAccess = setterAccess?.takeIf { it != propertyAccess } val propertyInfo = PropertyInfo(Identifier.withNoPrototype(propertyName), isVar, diff --git a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/AccessorToPropertyProcessing.kt b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/AccessorToPropertyProcessing.kt index d3613e2d474..39be60e8c9d 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/AccessorToPropertyProcessing.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/AccessorToPropertyProcessing.kt @@ -22,7 +22,6 @@ import org.jetbrains.kotlin.j2k.CodeConverter import org.jetbrains.kotlin.j2k.ast.* import org.jetbrains.kotlin.j2k.dot import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class AccessorToPropertyProcessing(val accessorMethod: PsiMethod, val accessorKind: AccessorKind, val propertyName: String) : UsageProcessing { override val targetElement: PsiElement get() = accessorMethod @@ -42,7 +41,7 @@ class AccessorToPropertyProcessing(val accessorMethod: PsiMethod, val accessorKi propertyName if (accessorKind == AccessorKind.GETTER) { - if (arguments.size != 0) return null // incorrect call + if (arguments.isNotEmpty()) return null // incorrect call return propertyAccess } else { @@ -59,7 +58,7 @@ class AccessorToPropertyProcessing(val accessorMethod: PsiMethod, val accessorKi if (accessorMethod.hasModifierProperty(PsiModifier.PRIVATE)) emptyList() else - AccessorToPropertyProcessor().singletonList() + listOf(AccessorToPropertyProcessor()) inner class AccessorToPropertyProcessor: ExternalCodeProcessor { override fun processUsage(reference: PsiReference): Array? { diff --git a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt index 2b0a95e01d7..111bc545e81 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt @@ -23,7 +23,6 @@ import org.jetbrains.kotlin.j2k.AccessorKind import org.jetbrains.kotlin.j2k.CodeConverter import org.jetbrains.kotlin.j2k.ast.* import org.jetbrains.kotlin.j2k.dot -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class FieldToPropertyProcessing( private val field: PsiField, @@ -43,11 +42,11 @@ class FieldToPropertyProcessing( else if (field.name != propertyName) listOf(ElementRenamedCodeProcessor(propertyName), UseAccessorsJavaCodeProcessor()) else - UseAccessorsJavaCodeProcessor().singletonList() + listOf(UseAccessorsJavaCodeProcessor()) override val kotlinCodeProcessors = if (field.name != propertyName) - ElementRenamedCodeProcessor(propertyName).singletonList() + listOf(ElementRenamedCodeProcessor(propertyName)) else emptyList() diff --git a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/MemberIntoObjectProcessing.kt b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/MemberIntoObjectProcessing.kt index 55cba32a629..79c47a838eb 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/MemberIntoObjectProcessing.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/MemberIntoObjectProcessing.kt @@ -17,14 +17,13 @@ package org.jetbrains.kotlin.j2k.usageProcessing import com.intellij.psi.* -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class MemberIntoObjectProcessing(private val member: PsiMember, private val objectName: String) : UsageProcessing { override val targetElement: PsiElement get() = member override val convertedCodeProcessor: ConvertedCodeProcessor? get() = null - override val javaCodeProcessors = AppendObjectNameProcessor().singletonList() + override val javaCodeProcessors = listOf(AppendObjectNameProcessor()) override val kotlinCodeProcessors = emptyList() diff --git a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/ToObjectWithOnlyMethodsProcessing.kt b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/ToObjectWithOnlyMethodsProcessing.kt index 08eb0000a04..834f6ca6a7c 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/ToObjectWithOnlyMethodsProcessing.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/ToObjectWithOnlyMethodsProcessing.kt @@ -18,14 +18,13 @@ package org.jetbrains.kotlin.j2k.usageProcessing import com.intellij.psi.* import org.jetbrains.kotlin.load.java.JvmAbi -import org.jetbrains.kotlin.utils.addToStdlib.singletonList class ToObjectWithOnlyMethodsProcessing(private val psiClass: PsiClass) : UsageProcessing { override val targetElement: PsiElement get() = psiClass override val convertedCodeProcessor: ConvertedCodeProcessor? get() = null - override val javaCodeProcessors = ToObjectWithOnlyMethodsProcessor().singletonList() + override val javaCodeProcessors = listOf(ToObjectWithOnlyMethodsProcessor()) override val kotlinCodeProcessors = emptyList() diff --git a/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterMultiFileTest.kt b/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterMultiFileTest.kt index cff042676a0..19166fc34cd 100644 --- a/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterMultiFileTest.kt +++ b/j2k/tests/org/jetbrains/kotlin/j2k/AbstractJavaToKotlinConverterMultiFileTest.kt @@ -36,7 +36,7 @@ abstract class AbstractJavaToKotlinConverterMultiFileTest : AbstractJavaToKotlin val project = LightPlatformTestCase.getProject()!! val psiManager = PsiManager.getInstance(project) - val filesToConvert = File(dirPath).listFiles { file, name -> name.endsWith(".java") } + val filesToConvert = File(dirPath).listFiles { _, name -> name.endsWith(".java") } val psiFilesToConvert = ArrayList() for (javaFile in filesToConvert) { val virtualFile = addFile(javaFile, "test") @@ -44,7 +44,7 @@ abstract class AbstractJavaToKotlinConverterMultiFileTest : AbstractJavaToKotlin psiFilesToConvert.add(psiFile) } - val externalFiles = File(dirPath + File.separator + "external").listFiles { file, name -> name.endsWith(".java") || name.endsWith(".kt") } + val externalFiles = File(dirPath + File.separator + "external").listFiles { _, name -> name.endsWith(".java") || name.endsWith(".kt") } val externalPsiFiles = ArrayList() for (file in externalFiles) { val virtualFile = addFile(file, "test") diff --git a/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/AbstractLookupTrackerTest.kt b/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/AbstractLookupTrackerTest.kt index e711b055b75..0040e9e183f 100644 --- a/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/AbstractLookupTrackerTest.kt +++ b/jps-plugin/jps-tests/test/org/jetbrains/kotlin/jps/build/AbstractLookupTrackerTest.kt @@ -37,7 +37,7 @@ abstract class AbstractLookupTrackerTest : AbstractIncrementalJpsTest( val COMMENT_WITH_LOOKUP_INFO = "/\\*[^*]+\\*/".toRegex() override fun checkLookups(lookupTracker: LookupTracker, compiledFiles: Set) { - if (lookupTracker !is TestLookupTracker) throw AssertionError("Expected TestLookupTracker, but: ${lookupTracker.javaClass}") + if (lookupTracker !is TestLookupTracker) throw AssertionError("Expected TestLookupTracker, but: ${lookupTracker::class.java}") val fileToLookups = lookupTracker.lookups.groupBy { it.filePath } diff --git a/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/JpsKotlinCompilerRunner.kt b/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/JpsKotlinCompilerRunner.kt index 68227368eed..ac426c7192d 100644 --- a/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/JpsKotlinCompilerRunner.kt +++ b/jps-plugin/src/org/jetbrains/kotlin/compilerRunner/JpsKotlinCompilerRunner.kt @@ -207,7 +207,7 @@ class JpsKotlinCompilerRunner : KotlinCompilerRunner() { private fun getReturnCodeFromObject(rc: Any?): String { when { rc == null -> return INTERNAL_ERROR - ExitCode::class.java.name == rc.javaClass.name -> return rc.toString() + ExitCode::class.java.name == rc::class.java.name -> return rc.toString() else -> throw IllegalStateException("Unexpected return: " + rc) } } diff --git a/jps-plugin/src/org/jetbrains/kotlin/jps/build/KotlinBuilder.kt b/jps-plugin/src/org/jetbrains/kotlin/jps/build/KotlinBuilder.kt index cf33b1e5ab7..920ffba1df3 100644 --- a/jps-plugin/src/org/jetbrains/kotlin/jps/build/KotlinBuilder.kt +++ b/jps-plugin/src/org/jetbrains/kotlin/jps/build/KotlinBuilder.kt @@ -450,7 +450,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) { messageCollector.report( INFO, - "Plugin loaded: ${argumentProvider.javaClass.simpleName}", + "Plugin loaded: ${argumentProvider::class.java.simpleName}", CompilerMessageLocation.NO_LOCATION ) } @@ -627,7 +627,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) { ) { if (!IncrementalCompilation.isExperimental()) return - if (lookupTracker !is LookupTrackerImpl) throw AssertionError("Lookup tracker is expected to be LookupTrackerImpl, got ${lookupTracker.javaClass}") + if (lookupTracker !is LookupTrackerImpl) throw AssertionError("Lookup tracker is expected to be LookupTrackerImpl, got ${lookupTracker::class.java}") val lookupStorage = dataManager.getStorage(KotlinDataContainerTarget, JpsLookupStorageProvider) diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/descriptorUtils/descriptorUtils.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/descriptorUtils/descriptorUtils.kt index 53ec5857f66..59693f96a05 100644 --- a/js/js.frontend/src/org/jetbrains/kotlin/js/descriptorUtils/descriptorUtils.kt +++ b/js/js.frontend/src/org/jetbrains/kotlin/js/descriptorUtils/descriptorUtils.kt @@ -25,10 +25,9 @@ import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.types.KotlinType -import org.jetbrains.kotlin.utils.addToStdlib.check val KotlinType.nameIfStandardType: Name? - get() = constructor.declarationDescriptor?.check(KotlinBuiltIns::isBuiltIn)?.name + get() = constructor.declarationDescriptor?.takeIf(KotlinBuiltIns::isBuiltIn)?.name fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String { val declaration = requireNotNull(constructor.declarationDescriptor) diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt index 18729790e29..fa9a271f2bd 100644 --- a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt +++ b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt @@ -32,7 +32,6 @@ import org.jetbrains.kotlin.resolve.checkers.SimpleDeclarationChecker import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeUtils -import org.jetbrains.kotlin.utils.singletonOrEmptyList object JsExternalChecker : SimpleDeclarationChecker { val DEFINED_EXTERNALLY_PROPERTY_NAMES = setOf(FqNameUnsafe("kotlin.js.noImpl"), FqNameUnsafe("kotlin.js.definedExternally")) @@ -79,7 +78,7 @@ object JsExternalChecker : SimpleDeclarationChecker { } if (descriptor is ClassDescriptor && descriptor.kind != ClassKind.ANNOTATION_CLASS) { - val superClasses = (descriptor.getSuperClassNotAny().singletonOrEmptyList() + descriptor.getSuperInterfaces()).toMutableSet() + val superClasses = (listOfNotNull(descriptor.getSuperClassNotAny()) + descriptor.getSuperInterfaces()).toMutableSet() if (descriptor.kind == ClassKind.ENUM_CLASS || descriptor.kind == ClassKind.ENUM_ENTRY) { superClasses.removeAll { it.fqNameUnsafe == KotlinBuiltIns.FQ_NAMES._enum } } diff --git a/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/WhileConditionFolding.kt b/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/WhileConditionFolding.kt index 0a0f3133749..5a90ada6a93 100644 --- a/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/WhileConditionFolding.kt +++ b/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/WhileConditionFolding.kt @@ -135,7 +135,7 @@ class WhileConditionFolding(val body: JsBlock) { // applying this rule repeatedly we get while (A && (B || C)), which is correct is JsIf -> { - val then = statement.thenStatement!! + val then = statement.thenStatement if (statement.elseStatement == null) { val nextCondition = extractCondition(then, label) val result: JsExpression? = when (nextCondition) { diff --git a/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/removeDefaultInitializers.kt b/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/removeDefaultInitializers.kt index c416734ae12..cbcbcec6e73 100644 --- a/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/removeDefaultInitializers.kt +++ b/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/removeDefaultInitializers.kt @@ -46,7 +46,7 @@ fun removeDefaultInitializers(arguments: List, parameters: List listOf() name != null && name in toExpand -> - flattenStatement((it as JsIf).thenStatement!!) + flattenStatement((it as JsIf).thenStatement) else -> listOf(it) } @@ -91,7 +91,7 @@ private fun isNameInitialized( name: JsName, initializer: JsStatement ): Boolean { - val thenStmt = (initializer as JsIf).thenStatement!! + val thenStmt = (initializer as JsIf).thenStatement val lastThenStmt = flattenStatement(thenStmt).last() val expr = (lastThenStmt as? JsExpressionStatement)?.expression diff --git a/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/MultiModuleOrderTest.kt b/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/MultiModuleOrderTest.kt index cecbf8887b2..670ccbd74aa 100644 --- a/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/MultiModuleOrderTest.kt +++ b/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/MultiModuleOrderTest.kt @@ -42,7 +42,7 @@ class MultiModuleOrderTest : BasicBoxTest("$TEST_DATA_DIR_PATH/multiModuleOrder/ val mainJsFile = File(parentDir, "$name-main_v5.js").path val libJsFile = File(parentDir, "$name-lib_v5.js").path try { - RhinoUtils.runRhinoTest(listOf(mainJsFile, libJsFile), RhinoResultChecker { context, scope -> + RhinoUtils.runRhinoTest(listOf(mainJsFile, libJsFile), RhinoResultChecker { _, _ -> // don't check anything, expect exception from function }) } diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt index 3f6e29aff9c..3b10088b544 100644 --- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt +++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt @@ -310,7 +310,7 @@ object DynamicOperatorCallCase : FunctionCallCase() { @Suppress("USELESS_CAST") (JsPostfixOperation(OperatorTable.getUnaryOperator(operationToken), dispatchReceiver) as JsExpression) } - else -> unsupported("Unsupported callElement type: ${callElement.javaClass}, callElement: $callElement, callInfo: $this") + else -> unsupported("Unsupported callElement type: ${callElement::class.java}, callElement: $callElement, callInfo: $this") } } } diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/UsageTracker.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/UsageTracker.kt index 86dd7450e02..61817c5de6d 100644 --- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/UsageTracker.kt +++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/UsageTracker.kt @@ -201,8 +201,8 @@ private fun ReceiverParameterDescriptor.getNameForCapturedReceiver(): String { val containingDeclaration = this.containingDeclaration assert(containingDeclaration is MemberDescriptor) { - "Unsupported descriptor type: ${containingDeclaration.javaClass}, " + - "receiverDescriptor = $this, " +"containingDeclaration = $containingDeclaration" + "Unsupported descriptor type: ${containingDeclaration::class.java}, " + + "receiverDescriptor = $this, " + "containingDeclaration = $containingDeclaration" } if (DescriptorUtils.isCompanionObject(containingDeclaration)) { diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/PropertyTranslator.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/PropertyTranslator.kt index 8d1103960e3..6b71860b1b4 100644 --- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/PropertyTranslator.kt +++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/PropertyTranslator.kt @@ -255,7 +255,7 @@ private class PropertyTranslator( is PropertySetterDescriptor, is LocalVariableAccessorDescriptor.Setter -> "setter" else -> - throw IllegalArgumentException("Unknown accessor type ${accessorDescriptor.javaClass}") + throw IllegalArgumentException("Unknown accessor type ${accessorDescriptor::class.java}") } val name = accessorDescriptor.name.asString() diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/expression/LoopTranslator.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/expression/LoopTranslator.kt index 1e87f41dc95..a1ffa57a1f7 100644 --- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/expression/LoopTranslator.kt +++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/expression/LoopTranslator.kt @@ -36,7 +36,6 @@ import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.psi.KtWhileExpressionBase import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe -import org.jetbrains.kotlin.utils.singletonOrEmptyList fun createWhile(doWhile: Boolean, expression: KtWhileExpressionBase, context: TranslationContext): JsNode { val conditionExpression = expression.condition ?: @@ -121,7 +120,7 @@ fun translateForExpression(expression: KtForExpression, context: TranslationCont destructuringParameter, parameterName, itemValue, context.innerBlock(block)) } block.statements += currentVarInit - block.statements += if (realBody is JsBlock) realBody.statements else realBody.singletonOrEmptyList() + block.statements += if (realBody is JsBlock) realBody.statements else listOfNotNull(realBody) return block } diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/intrinsic/functions/basic/RangeToIntrinsic.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/intrinsic/functions/basic/RangeToIntrinsic.kt index 7d9b65b3e47..bc949c566e2 100644 --- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/intrinsic/functions/basic/RangeToIntrinsic.kt +++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/intrinsic/functions/basic/RangeToIntrinsic.kt @@ -24,7 +24,6 @@ import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.reference.ReferenceTranslator import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter -import org.jetbrains.kotlin.utils.singletonOrEmptyList class RangeToIntrinsic(function: FunctionDescriptor) : FunctionIntrinsicWithReceiverComputed() { val rangeTypeDescriptor = function.returnType!!.constructor.declarationDescriptor as ClassDescriptor @@ -37,6 +36,6 @@ class RangeToIntrinsic(function: FunctionDescriptor) : FunctionIntrinsicWithRece } val finalClass = (existingClasses.firstOrNull() as? ClassDescriptor) ?: rangeTypeDescriptor val constructor = ReferenceTranslator.translateAsTypeReference(finalClass, context) - return JsNew(constructor, receiver.singletonOrEmptyList() + arguments) + return JsNew(constructor, listOfNotNull(receiver) + arguments) } } \ No newline at end of file diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/utils/astUtils.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/utils/astUtils.kt index 4aa50030199..4f669a033e3 100644 --- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/utils/astUtils.kt +++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/utils/astUtils.kt @@ -76,7 +76,7 @@ fun JsExpression.toInvocationWith( // `A(a, b, c)` -> `A(a, b, c, $this)` return JsInvocation(qualifier, leadingExtraArgs + padArguments(arguments) + thisExpr) } - else -> throw IllegalStateException("Unexpected node type: " + javaClass) + else -> throw IllegalStateException("Unexpected node type: " + this::class.java) } } diff --git a/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/AndroidSyntheticPackageFragmentDescriptor.kt b/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/AndroidSyntheticPackageFragmentDescriptor.kt index cd4567886d7..14d5b8c3a7e 100644 --- a/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/AndroidSyntheticPackageFragmentDescriptor.kt +++ b/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/AndroidSyntheticPackageFragmentDescriptor.kt @@ -84,7 +84,7 @@ class AndroidSyntheticPackageFragmentDescriptor( override fun getContributedVariables(name: Name, location: LookupLocation) = properties().filter { it.name == name } override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName) + p.println(this::class.java.simpleName) } } } diff --git a/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/PredefinedPackageFragmentDescriptor.kt b/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/PredefinedPackageFragmentDescriptor.kt index 28be965011f..5fc1761dda7 100644 --- a/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/PredefinedPackageFragmentDescriptor.kt +++ b/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/descriptors/PredefinedPackageFragmentDescriptor.kt @@ -55,7 +55,7 @@ class PredefinedPackageFragmentDescriptor( calculatedFunctions().filter { nameFilter(it.name) && kindFilter.accepts(it) } override fun printScopeStructure(p: Printer) { - p.println(javaClass.simpleName) + p.println(this::class.java.simpleName) } } } diff --git a/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/res/androidResources.kt b/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/res/androidResources.kt index ec2f2af59c8..9e6a7de280f 100644 --- a/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/res/androidResources.kt +++ b/plugins/android-extensions/android-extensions-compiler/src/org/jetbrains/kotlin/android/synthetic/res/androidResources.kt @@ -48,7 +48,7 @@ class ResourceIdentifier(val name: String, val packageName: String?) { // Without packageName override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as ResourceIdentifier diff --git a/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/AndroidXmlVisitor.kt b/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/AndroidXmlVisitor.kt index 1a507615c09..50399fe18d7 100644 --- a/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/AndroidXmlVisitor.kt +++ b/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/AndroidXmlVisitor.kt @@ -47,7 +47,7 @@ class AndroidXmlVisitor(val elementCallback: (ResourceIdentifier, String, XmlAtt if (idAttribute != null) { val idAttributeValue = idAttribute.value if (idAttributeValue != null) { - val xmlType = tag?.getAttribute(AndroidConst.CLASS_ATTRIBUTE_NO_NAMESPACE)?.value ?: localName + val xmlType = tag.getAttribute(AndroidConst.CLASS_ATTRIBUTE_NO_NAMESPACE)?.value ?: localName val name = androidIdToName(idAttributeValue) if (name != null) elementCallback(name, xmlType, idAttribute) } diff --git a/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/res/IDEAndroidLayoutXmlFileManager.kt b/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/res/IDEAndroidLayoutXmlFileManager.kt index af0c7ddd41a..2716626887f 100644 --- a/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/res/IDEAndroidLayoutXmlFileManager.kt +++ b/plugins/android-extensions/android-extensions-idea/src/org/jetbrains/kotlin/android/synthetic/idea/res/IDEAndroidLayoutXmlFileManager.kt @@ -83,7 +83,7 @@ class IDEAndroidLayoutXmlFileManager(val module: Module) : AndroidLayoutXmlFileM val propertyName = propertyDescriptor.name.asString() val attributes = arrayListOf() - val visitor = AndroidXmlVisitor { retId, wClass, valueElement -> + val visitor = AndroidXmlVisitor { retId, _, valueElement -> if (retId.name == propertyName) attributes.add(valueElement) } @@ -114,7 +114,7 @@ class IDEAndroidLayoutXmlFileManager(val module: Module) : AndroidLayoutXmlFileM if (applicationPackage != null) { val mainVariant = mainSourceProvider.toVariant() - val method = try { javaClass.getMethod("getFlavorSourceProviders") } catch (e: NoSuchMethodException) { null } + val method = try { this::class.java.getMethod("getFlavorSourceProviders") } catch (e: NoSuchMethodException) { null } val variants: List? = if (method != null) { val sourceProviders = method.invoke(this) as List? sourceProviders?.map { it.toVariant() } ?: listOf() diff --git a/plugins/android-extensions/android-extensions-idea/tests/org/jetbrains/kotlin/android/AbstractAndroidGotoTest.kt b/plugins/android-extensions/android-extensions-idea/tests/org/jetbrains/kotlin/android/AbstractAndroidGotoTest.kt index 4ee733c22f4..51255565669 100644 --- a/plugins/android-extensions/android-extensions-idea/tests/org/jetbrains/kotlin/android/AbstractAndroidGotoTest.kt +++ b/plugins/android-extensions/android-extensions-idea/tests/org/jetbrains/kotlin/android/AbstractAndroidGotoTest.kt @@ -48,7 +48,7 @@ abstract class AbstractAndroidGotoTest : KotlinAndroidTestCase() { val targetElement = GotoDeclarationAction.findTargetElement(f.project, f.editor, f.caretOffset)!! - assert(targetElement is XmlAttributeValue) { "XmlAttributeValue expected, got ${targetElement.javaClass}" } + assert(targetElement is XmlAttributeValue) { "XmlAttributeValue expected, got ${targetElement::class.java}" } assertEquals("@+id/${property.name}", (targetElement as XmlAttributeValue).value) } } \ No newline at end of file diff --git a/plugins/android-extensions/android-extensions-jps/src/KotlinAndroidJpsPlugin.kt b/plugins/android-extensions/android-extensions-jps/src/KotlinAndroidJpsPlugin.kt index b6798e3c64a..4d30dae6104 100644 --- a/plugins/android-extensions/android-extensions-jps/src/KotlinAndroidJpsPlugin.kt +++ b/plugins/android-extensions/android-extensions-jps/src/KotlinAndroidJpsPlugin.kt @@ -62,16 +62,16 @@ class KotlinAndroidJpsPlugin : KotlinJpsCompilerArgumentsProvider { val module = moduleBuildTarget.module if (!hasAndroidJpsPlugin() || !isAndroidModuleWithoutGradle(module)) return emptyList() - val inJar = File(PathUtil.getJarPathForClass(javaClass)).isFile + val inJar = File(PathUtil.getJarPathForClass(this::class.java)).isFile val manifestFile = getAndroidManifest(moduleBuildTarget.module) return if (manifestFile != null) { listOf( if (inJar) { - val libDirectory = File(PathUtil.getJarPathForClass(javaClass)).parentFile.parentFile + val libDirectory = File(PathUtil.getJarPathForClass(this::class.java)).parentFile.parentFile File(libDirectory, JAR_FILE_NAME).absolutePath } else { // We're in tests now (in out/production/android-extensions/android-extensions-jps) - val kotlinProjectDirectory = File(PathUtil.getJarPathForClass(javaClass)).parentFile.parentFile.parentFile + val kotlinProjectDirectory = File(PathUtil.getJarPathForClass(this::class.java)).parentFile.parentFile.parentFile File(kotlinProjectDirectory, "dist/kotlinc/lib/$JAR_FILE_NAME").absolutePath }) } diff --git a/plugins/annotation-based-compiler-plugins-ide-support/src/AbstractGradleImportHandler.kt b/plugins/annotation-based-compiler-plugins-ide-support/src/AbstractGradleImportHandler.kt index 71dab3f9b2e..b3d25328f56 100644 --- a/plugins/annotation-based-compiler-plugins-ide-support/src/AbstractGradleImportHandler.kt +++ b/plugins/annotation-based-compiler-plugins-ide-support/src/AbstractGradleImportHandler.kt @@ -60,7 +60,7 @@ abstract class AbstractGradleImportHandler : GradleProjectImportHandler { }?.data as? TaskData ?: return null val dataStorageTaskDescription = dataStorageTaskData.description ?: return null - val (annotationFqNamesList, classpathList) = TASK_DESCRIPTION_REGEX.matchEntire( + val (annotationFqNamesList, _) = TASK_DESCRIPTION_REGEX.matchEntire( dataStorageTaskDescription)?.groupValues?.drop(1) ?: return null val annotationFqNames = annotationFqNamesList.split(',') diff --git a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/AnnotationProcessingExtension.kt b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/AnnotationProcessingExtension.kt index 250f0ff1ba9..93fb08691ca 100755 --- a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/AnnotationProcessingExtension.kt +++ b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/AnnotationProcessingExtension.kt @@ -202,7 +202,7 @@ abstract class AbstractAnnotationProcessingExtension( private fun KotlinProcessingEnvironment.doAnnotationProcessing(files: Collection): ProcessingResult { run initializeProcessors@ { processors().forEach { it.init(this) } - log { "Initialized processors: " + processors().joinToString { it.javaClass.name } } + log { "Initialized processors: " + processors().joinToString { it::class.java.name } } } val firstRoundAnnotations = RoundAnnotations( @@ -334,7 +334,7 @@ abstract class AbstractAnnotationProcessingExtension( } if (applicableAnnotationNames.isEmpty()) { - log { "Skipping processor " + processor.javaClass.name + ": no relevant annotations" } + log { "Skipping processor " + processor::class.java.name + ": no relevant annotations" } continue } @@ -344,7 +344,7 @@ abstract class AbstractAnnotationProcessingExtension( log { val annotationNames = applicableAnnotations.joinToString { it.qualifiedName.toString() } - "Processing with " + processor.javaClass.name + " (annotations: " + annotationNames + ")" + "Processing with " + processor::class.java.name + " (annotations: " + annotationNames + ")" } processor.process(applicableAnnotations, roundEnvironment) diff --git a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt index f00b43afc52..7b2520dbd36 100644 --- a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt +++ b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt @@ -92,7 +92,7 @@ class KotlinElements( override fun printElements(w: Writer, vararg elements: Element) { val printWriter = PrintWriter(w) for (element in elements) { - printWriter.println(element.simpleName.toString() + " (" + element.javaClass.name + ")") + printWriter.println(element.simpleName.toString() + " (" + element::class.java.name + ")") } } @@ -177,7 +177,7 @@ object Constants { is Int, is Boolean -> value.toString() else -> throw IllegalArgumentException( "Argument is not a primitive type or a string; it " + - (if (value == null) "is a null value." else "has class " + value.javaClass.name) + ".") + (if (value == null) "is a null value." else "has class " + value::class.java.name) + ".") } } diff --git a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt index 0b184a5cc16..31f69d76b2c 100644 --- a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt +++ b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt @@ -267,7 +267,7 @@ class KotlinTypes( } is JeVariableElement -> substitutor.substitute(element.psi.type).toJeType(psiManager()) is JeTypeParameterElement -> substitutor.substitute(element.psi)?.toJeType(psiManager()) ?: element.asType() - else -> throw IllegalArgumentException("Invalid element type: ${element.javaClass.name} ($element)") + else -> throw IllegalArgumentException("Invalid element type: ${element::class.java.name} ($element)") } } @@ -308,6 +308,6 @@ private fun assertKindNot(typeMirror: TypeMirror, vararg kinds: TypeKind): Unit private fun assertJeType(type: TypeMirror) { if (type !is JeTypeMirror) { - illegalArg("Must be a subclass of JePsiType, got ${type.javaClass.name}") + illegalArg("Must be a subclass of JePsiType, got ${type::class.java.name}") } } \ No newline at end of file diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeClassInitializerExecutableElement.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeClassInitializerExecutableElement.kt index 1d190075db0..2af50bc56a1 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeClassInitializerExecutableElement.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeClassInitializerExecutableElement.kt @@ -59,7 +59,7 @@ class JeClassInitializerExecutableElement( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as JeClassInitializerExecutableElement).psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeMethodExecutableElement.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeMethodExecutableElement.kt index 52fb2990f3e..3b2e3f31360 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeMethodExecutableElement.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeMethodExecutableElement.kt @@ -67,7 +67,7 @@ class JeMethodExecutableElement(psi: PsiMethod) : JeAbstractElement(p override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as JeMethodExecutableElement).psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JePackageElement.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JePackageElement.kt index e1994e6c3e6..bc91bac06bd 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JePackageElement.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JePackageElement.kt @@ -42,7 +42,7 @@ class JePackageElement(psi: PsiPackage) : JeAbstractElement(psi), Pa override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as JePackageElement).psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeElement.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeElement.kt index 278fa163da3..96bd09d10f3 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeElement.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeElement.kt @@ -131,7 +131,7 @@ class JeTypeElement(psi: PsiClass) : JeAbstractElement(psi), TypeEleme override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as JeTypeElement).psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeParameterElement.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeParameterElement.kt index ea460896f51..7edad08318d 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeParameterElement.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeTypeParameterElement.kt @@ -47,7 +47,7 @@ class JeTypeParameterElement( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as JeTypeParameterElement).psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeVariableElement.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeVariableElement.kt index c9bfb47d2c6..708dd97bda7 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeVariableElement.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/elements/JeVariableElement.kt @@ -56,7 +56,7 @@ class JeVariableElement(psi: PsiVariable) : JeAbstractElement(psi), override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as JeVariableElement).psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/internal/KotlinAnnotationProxyMaker.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/internal/KotlinAnnotationProxyMaker.kt index 4452e078fd1..8634ef4a035 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/internal/KotlinAnnotationProxyMaker.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/internal/KotlinAnnotationProxyMaker.kt @@ -140,7 +140,7 @@ private fun getObjectType(value: PsiAnnotationMemberValue): PsiType { } } - throw IllegalArgumentException("Illegal value type: ${value.javaClass}") + throw IllegalArgumentException("Illegal value type: ${value::class.java}") } private fun castPrimitiveValue(type: PsiType, value: Any?): Any = when (type) { diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeArrayType.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeArrayType.kt index 6157c700b77..1c431fdafbb 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeArrayType.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeArrayType.kt @@ -35,7 +35,7 @@ class JeArrayType( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as? JeArrayType ?: return false return componentType == other.componentType diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeClassInitializerExecutableTypeMirror.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeClassInitializerExecutableTypeMirror.kt index ddd62b518d4..733fa9a027e 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeClassInitializerExecutableTypeMirror.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeClassInitializerExecutableTypeMirror.kt @@ -43,7 +43,7 @@ class JeClassInitializerExecutableTypeMirror( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as? JeClassInitializerExecutableTypeMirror ?: return false return psi == other.psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeDeclaredType.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeDeclaredType.kt index 5f7fcdb6c5b..9ae2bf185b0 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeDeclaredType.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeDeclaredType.kt @@ -100,7 +100,7 @@ class JeDeclaredType( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as? JeDeclaredType ?: return false return enclosingType == other.enclosingType diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeIntersectionType.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeIntersectionType.kt index 11658e98e79..3148c86a8bf 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeIntersectionType.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeIntersectionType.kt @@ -34,7 +34,7 @@ class JeIntersectionType( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as? JeIntersectionType ?: return false return bounds == other.bounds diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeMethodExecutableTypeMirror.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeMethodExecutableTypeMirror.kt index d2915304678..e928d3b865b 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeMethodExecutableTypeMirror.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeMethodExecutableTypeMirror.kt @@ -87,7 +87,7 @@ class JeMethodExecutableTypeMirror( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psi == (other as? JeMethodExecutableTypeMirror)?.psi } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JePrimitiveType.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JePrimitiveType.kt index feffc97b18d..f2f224dc07f 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JePrimitiveType.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JePrimitiveType.kt @@ -42,7 +42,7 @@ class JePrimitiveType(override val psiType: PsiPrimitiveType) : JePsiType, Primi override fun equals(other: Any?): Boolean{ if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psiType == (other as? JePrimitiveType)?.psiType } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeTypeVariableType.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeTypeVariableType.kt index f1751537eb3..cb9723c87cd 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeTypeVariableType.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeTypeVariableType.kt @@ -65,7 +65,7 @@ class JeTypeVariableType( override fun equals(other: Any?): Boolean{ if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return psiType == (other as? JeTypeVariableType)?.psiType } diff --git a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeWildcardType.kt b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeWildcardType.kt index 4ff0b298b02..877ff40f83b 100644 --- a/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeWildcardType.kt +++ b/plugins/java-model-wrappers/src/org/jetbrains/kotlin/java/model/types/JeWildcardType.kt @@ -35,7 +35,7 @@ class JeWildcardType( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as? JeWildcardType ?: return false return superBound == other.superBound @@ -70,7 +70,7 @@ class JeCapturedWildcardType( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as? JeCapturedWildcardType ?: return false return superBound == other.superBound diff --git a/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/Kapt3Extension.kt b/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/Kapt3Extension.kt index d971752f337..2b48e24c924 100644 --- a/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/Kapt3Extension.kt +++ b/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/Kapt3Extension.kt @@ -86,7 +86,7 @@ class ClasspathBasedKapt3Extension( if (processors.isEmpty()) { logger.info("No annotation processors available, aborting") } else { - logger.info { "Annotation processors: " + processors.joinToString { it.javaClass.canonicalName } } + logger.info { "Annotation processors: " + processors.joinToString { it::class.java.canonicalName } } } return processors diff --git a/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/javac/KaptJavaFileObject.kt b/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/javac/KaptJavaFileObject.kt index 0f3b395dd4b..4fba5f6f6ec 100644 --- a/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/javac/KaptJavaFileObject.kt +++ b/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/javac/KaptJavaFileObject.kt @@ -79,7 +79,7 @@ class KaptJavaFileObject( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false other as KaptJavaFileObject diff --git a/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/stubs/ClassFileToSourceStubConverter.kt b/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/stubs/ClassFileToSourceStubConverter.kt index a8138f9e5b5..b18c0c33fd4 100644 --- a/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/stubs/ClassFileToSourceStubConverter.kt +++ b/plugins/kapt3/src/org/jetbrains/kotlin/kapt3/stubs/ClassFileToSourceStubConverter.kt @@ -632,7 +632,7 @@ class ClassFileToSourceStubConverter( is Type -> treeMaker.Select(treeMaker.Type(value), treeMaker.name("class")) is AnnotationNode -> convertAnnotation(value, packageFqName = null, filtered = false)!! - else -> throw IllegalArgumentException("Illegal literal expression value: $value (${value.javaClass.canonicalName})") + else -> throw IllegalArgumentException("Illegal literal expression value: $value (${value::class.java.canonicalName})") } } diff --git a/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/AbstractKotlinKapt3IntegrationTest.kt b/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/AbstractKotlinKapt3IntegrationTest.kt index 13477bad934..09c86c6025b 100644 --- a/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/AbstractKotlinKapt3IntegrationTest.kt +++ b/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/AbstractKotlinKapt3IntegrationTest.kt @@ -70,7 +70,7 @@ abstract class AbstractKotlinKapt3IntegrationTest : CodegenTestCase() { name: String, vararg supportedAnnotations: String, options: Map = emptyMap() - ) = testAP(false, name, options, { set, roundEnv, env -> fail("Should not run") }, *supportedAnnotations) + ) = testAP(false, name, options, { _, _, _ -> fail("Should not run") }, *supportedAnnotations) protected fun testAP( shouldRun: Boolean, diff --git a/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/KotlinKapt3IntegrationTests.kt b/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/KotlinKapt3IntegrationTests.kt index 0c17b7da2b8..26958e31986 100644 --- a/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/KotlinKapt3IntegrationTests.kt +++ b/plugins/kapt3/test/org/jetbrains/kotlin/kapt3/test/KotlinKapt3IntegrationTests.kt @@ -26,7 +26,7 @@ import javax.lang.model.element.ExecutableElement class KotlinKapt3IntegrationTests : AbstractKotlinKapt3IntegrationTest() { @Test - fun testSimple() = test("Simple", "test.MyAnnotation") { set, roundEnv, env -> + fun testSimple() = test("Simple", "test.MyAnnotation") { set, roundEnv, _ -> assertEquals(1, set.size) val annotatedElements = roundEnv.getElementsAnnotatedWith(set.single()) assertEquals(1, annotatedElements.size) @@ -63,7 +63,7 @@ class KotlinKapt3IntegrationTests : AbstractKotlinKapt3IntegrationTest() { } private fun bindingsTest(name: String, test: (File, File, Map) -> Unit) { - test(name, "test.MyAnnotation") { set, roundEnv, env -> + test(name, "test.MyAnnotation") { _, _, _ -> val kaptExtension = AnalysisHandlerExtension.getInstances(myEnvironment.project).firstIsInstance() val stubsOutputDir = kaptExtension.stubsOutputDir @@ -79,14 +79,14 @@ class KotlinKapt3IntegrationTests : AbstractKotlinKapt3IntegrationTest() { fun testOptions() = test( "Simple", "test.MyAnnotation", options = mapOf("firstKey" to "firstValue", "secondKey" to "") - ) { set, roundEnv, env -> + ) { _, _, env -> val options = env.options assertEquals("firstValue", options["firstKey"]) assertTrue("secondKey" in options) } @Test - fun testOverloads() = test("Overloads", "test.MyAnnotation") { set, roundEnv, env -> + fun testOverloads() = test("Overloads", "test.MyAnnotation") { set, roundEnv, _ -> assertEquals(1, set.size) val annotatedElements = roundEnv.getElementsAnnotatedWith(set.single()) assertEquals(1, annotatedElements.size) diff --git a/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/AbstractProcessorTest.kt b/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/AbstractProcessorTest.kt index 5c33d4eea89..001365a9a97 100755 --- a/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/AbstractProcessorTest.kt +++ b/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/AbstractProcessorTest.kt @@ -108,7 +108,7 @@ abstract class AbstractProcessorTest : AbstractBytecodeTextTest() { protected fun testShouldNotRun( name: String, vararg supportedAnnotations: String - ) = testAP(false, name, { set, roundEnv, env -> fail("Should not run") }, *supportedAnnotations) + ) = testAP(false, name, { _, _, _ -> fail("Should not run") }, *supportedAnnotations) protected fun testAP( shouldRun: Boolean, diff --git a/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ElementsTests.kt b/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ElementsTests.kt index 36809af49c9..8309f933ad1 100644 --- a/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ElementsTests.kt +++ b/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ElementsTests.kt @@ -25,7 +25,7 @@ import javax.lang.model.element.TypeElement class ElementsTests : AbstractProcessorTest() { override val testDataDir = "plugins/annotation-processing/testData/elements" - fun testOverrides() = test("Overrides", "*") { set, roundEnv, env -> + fun testOverrides() = test("Overrides", "*") { _, _, env -> val (parent, child, childChild) = Triple(env.findClass("Parent"), env.findClass("Child"), env.findClass("ChildOfChild")) val parentA = parent.findMethod("a") @@ -52,7 +52,7 @@ class ElementsTests : AbstractProcessorTest() { childChildACharSequence.assertOverrides(childA, false) } - fun testOverrides2() = test("Overrides2", "*") { set, roundEnv, env -> + fun testOverrides2() = test("Overrides2", "*") { _, _, env -> val classes = listOf(env.findClass("Intf"), env.findClass("A"), env.findClass("B")) val (intf, a, b) = classes.map { it.findMethod("a") } @@ -66,7 +66,7 @@ class ElementsTests : AbstractProcessorTest() { a.assertOverrides(intf, classes[2], true) } - fun testIsFunctionalInterface() = test("IsFunctionalInterface", "*") { set, roundEnv, env -> + fun testIsFunctionalInterface() = test("IsFunctionalInterface", "*") { _, _, env -> with (env.elementUtils as KotlinElements) { fun assertIsFunctionalInterface(fqName: String, isIntf: Boolean) { assertEquals(isIntf, isFunctionalInterface(env.findClass(fqName))) @@ -82,7 +82,7 @@ class ElementsTests : AbstractProcessorTest() { } } - fun testIsDeprecated() = test("IsDeprecated", "*") { set, roundEnv, env -> + fun testIsDeprecated() = test("IsDeprecated", "*") { _, _, env -> with (env.elementUtils) { assertEquals(true, isDeprecated(env.findClass("Depr"))) assertEquals(false, isDeprecated(env.findClass("NoDepr"))) @@ -90,7 +90,7 @@ class ElementsTests : AbstractProcessorTest() { } } - fun testGetElementValuesWithDefaults() = test("GetElementValuesWithDefaults", "Anno") { set, roundEnv, env -> + fun testGetElementValuesWithDefaults() = test("GetElementValuesWithDefaults", "Anno") { _, _, env -> val (a, b, c, d) = listOf(env.findClass("A"), env.findClass("B"), env.findClass("C"), env.findClass("D")) fun getValues(e: JeTypeElement) = env.elementUtils .getElementValuesWithDefaults(e.annotationMirrors.first { it.psi.qualifiedName == "Anno" }) @@ -102,7 +102,7 @@ class ElementsTests : AbstractProcessorTest() { assertEquals(listOf("Mary", 20), getValues(d)) } - fun testGetAllMembers() = test("GetAllMembers", "*") { set, roundEnv, env -> + fun testGetAllMembers() = test("GetAllMembers", "*") { _, _, env -> val clazz = env.findClass("MyClass") val members = clazz.enclosedElements assertEquals(5, members.size) // constructor, field, getter/setter, arbitrary method @@ -114,7 +114,7 @@ class ElementsTests : AbstractProcessorTest() { allMembers.sortedBy { it.simpleName.toString() }.joinToString { it.simpleName }) } - fun testGetPackageOf() = test("GetPackageOf", "*") { set, roundEnv, env -> + fun testGetPackageOf() = test("GetPackageOf", "*") { _, _, env -> val e = env.elementUtils val myClass = env.findClass("test.MyClass") @@ -130,7 +130,7 @@ class ElementsTests : AbstractProcessorTest() { assertEquals(3, classes.size) } - fun testGetArrayType() = test("GetPackageOf", "*") { set, roundEnv, env -> + fun testGetArrayType() = test("GetPackageOf", "*") { _, _, env -> val myClass = env.findClass("test.MyClass").asType() val array = env.typeUtils.getArrayType(myClass) assert(array is JeArrayType) diff --git a/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ProcessorTests.kt b/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ProcessorTests.kt index 7a1154c3770..e6d4bbc2346 100644 --- a/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ProcessorTests.kt +++ b/plugins/plugins-tests/tests/org/jetbrains/kotlin/annotation/processing/test/processor/ProcessorTests.kt @@ -38,7 +38,7 @@ annotation class ColorsAnnotation(val colors: Array) class ProcessorTests : AbstractProcessorTest() { override val testDataDir = "plugins/annotation-processing/testData/processors" - fun testSimple() = test("Simple", "Anno") { set, roundEnv, env -> + fun testSimple() = test("Simple", "Anno") { set, roundEnv, _ -> assertEquals(1, set.size) val annotated = roundEnv.getElementsAnnotatedWith(set.first()) assertEquals(3, annotated.size) @@ -52,7 +52,7 @@ class ProcessorTests : AbstractProcessorTest() { } } - fun testSeveralAnnotations() = test("SeveralAnnotations", "Name", "Age") { set, roundEnv, env -> + fun testSeveralAnnotations() = test("SeveralAnnotations", "Name", "Age") { set, roundEnv, _ -> val annos = set.toList() assertEquals(2, annos.size) @@ -70,15 +70,15 @@ class ProcessorTests : AbstractProcessorTest() { } } - fun testStar() = test("Star", "*") { set, roundEnv, env -> + fun testStar() = test("Star", "*") { set, _, _ -> assertEquals(true, set.any { it.qualifiedName.toString() == "Anno" }) } - fun testStar2() = test("Star", "Anno", "*") { set, roundEnv, env -> + fun testStar2() = test("Star", "Anno", "*") { set, _, _ -> assertEquals(true, set.any { it.qualifiedName.toString() == "Anno" }) } - fun testStar3() = test("Star3", "Anno", "*") { set, roundEnv, env -> + fun testStar3() = test("Star3", "Anno", "*") { set, _, _ -> assertEquals(true, set.any { it.qualifiedName.toString() == "Anno2" }) } @@ -87,7 +87,7 @@ class ProcessorTests : AbstractProcessorTest() { fun testInheritedAnnotations() { val handledClasses = mutableListOf() - test("InheritedAnnotations", "Anno") { set, roundEnv, env -> + test("InheritedAnnotations", "Anno") { set, roundEnv, _ -> assertEquals(1, set.size) val annotatedElements = roundEnv.getElementsAnnotatedWith(set.first()) for (element in annotatedElements) { @@ -103,7 +103,7 @@ class ProcessorTests : AbstractProcessorTest() { assertEquals(listOf("Base", "Impl", "Intf"), handledClasses.sorted()) } - fun testInheritedAnnotationsOverridden() = test("InheritedAnnotationsOverridden", "Anno") { set, roundEnv, env -> + fun testInheritedAnnotationsOverridden() = test("InheritedAnnotationsOverridden", "Anno") { set, roundEnv, _ -> assertEquals(1, set.size) val annotatedElements = roundEnv.getElementsAnnotatedWith(set.first()) assertEquals(2, annotatedElements.size) @@ -112,7 +112,7 @@ class ProcessorTests : AbstractProcessorTest() { assertEquals("Tom", implAnnotations.first().elementValues.values.first().value) } - fun testNested() = test("Nested", "Anno") { set, roundEnv, env -> + fun testNested() = test("Nested", "Anno") { set, roundEnv, _ -> assertEquals(1, set.size) val annotatedElements = roundEnv.getElementsAnnotatedWith(set.first()) assertEquals(1, annotatedElements.size) @@ -127,21 +127,21 @@ class ProcessorTests : AbstractProcessorTest() { assertTrue((anno2.getParam("e") as JeArrayAnnotationValue).value.first() is JeTypeAnnotationValue) } - fun testEnumArray() = test("EnumArray", "*") { set, roundEnv, env -> + fun testEnumArray() = test("EnumArray", "*") { _, _, env -> val testClass = env.findClass("org.jetbrains.kotlin.annotation.processing.test.processor.Test") val enumAnno = testClass.getAnnotation(ColorsAnnotation::class.java) assertNotNull(enumAnno) assertEquals(listOf("BLUE", "RED"), enumAnno!!.colors.map { it.name }) } - fun testStringArray() = test("StringArray", "*") { set, roundEnv, env -> + fun testStringArray() = test("StringArray", "*") { _, _, env -> val testClass = env.findClass("Test") val suppress = testClass.getAnnotation(Suppress::class.java) assertNotNull(suppress) assertEquals(listOf("Tom", "Mary"), suppress!!.names.toList()) } - fun testTypeArguments() = test("TypeArguments", "*") { set, roundEnv, env -> + fun testTypeArguments() = test("TypeArguments", "*") { _, _, env -> val classA = env.findClass("A") val superB = classA.superclass as JeDeclaredType val interfaceC = classA.interfaces[0] as JeDeclaredType @@ -150,7 +150,7 @@ class ProcessorTests : AbstractProcessorTest() { assertTrue(interfaceC.typeArguments.size == 1) } - fun testTypeArguments2() = test("TypeArguments2", "*") { set, roundEnv, env -> + fun testTypeArguments2() = test("TypeArguments2", "*") { _, _, env -> val b = env.findClass("B") val bSuperTypes = env.typeUtils.directSupertypes(b.asType()) assertEquals(1, bSuperTypes.size) @@ -182,7 +182,7 @@ class ProcessorTests : AbstractProcessorTest() { assertEquals("I3>", i3.toString()) } - fun testErasureSimple() = test("ErasureSimple", "*") { set, roundEnv, env -> + fun testErasureSimple() = test("ErasureSimple", "*") { _, _, env -> val test = env.findClass("Test") val int = test.findMethod("a").returnType val void = test.findMethod("b").returnType @@ -190,7 +190,7 @@ class ProcessorTests : AbstractProcessorTest() { assertEquals(void, env.typeUtils.erasure(void)) } - fun testErasure2() = test("Erasure2", "*") { set, roundEnv, env -> + fun testErasure2() = test("Erasure2", "*") { _, _, env -> val erasure = fun (t: JeMethodExecutableTypeMirror) = env.typeUtils.erasure(t) fun JeTypeElement.check(methodName: String, toString: String, transform: (JeMethodExecutableTypeMirror) -> TypeMirror = { it }) { val method = enclosedElements.first { it is JeMethodExecutableElement && it.simpleName.toString() == methodName } @@ -246,7 +246,7 @@ class ProcessorTests : AbstractProcessorTest() { .firstIsInstance() private fun incrementalDataTest(fileName: String, @Language("TEXT") expectedText: String) { - test(fileName, "Anno", "Anno2", "Anno3") { set, roundEnv, env -> } + test(fileName, "Anno", "Anno2", "Anno3") { _, _, _ -> } val ext = getKapt2Extension() val incrementalDataFile = ext.incrementalDataFile assertNotNull(incrementalDataFile) @@ -254,7 +254,7 @@ class ProcessorTests : AbstractProcessorTest() { assertEquals(expectedText, text) } - fun testKotlinAnnotationDefaultValueFromBinary() = test("DefaultValueFromBinary", "*") { set, roundEnv, env -> + fun testKotlinAnnotationDefaultValueFromBinary() = test("DefaultValueFromBinary", "*") { _, _, env -> fun check(expectedValue: Boolean, className: String) { val clazz = env.findClass(className) val anno = clazz.getAnnotation(JvmSuppressWildcards::class.java)!! @@ -266,7 +266,7 @@ class ProcessorTests : AbstractProcessorTest() { check(false, "TestFalse") } - fun testAsMemberOf() = test("AsMemberOf", "*") { set, roundEnv, env -> + fun testAsMemberOf() = test("AsMemberOf", "*") { _, _, env -> val f = env.findClass("Test").findField("f") val fType = f.asType() as JeDeclaredType @@ -290,7 +290,7 @@ class ProcessorTests : AbstractProcessorTest() { check(implM, "(java.lang.String)java.lang.String") } - fun testAsMemberOfTypeParameters() = test("AsMemberOfTypeParameters", "*") { set, roundEnv, env -> + fun testAsMemberOfTypeParameters() = test("AsMemberOfTypeParameters", "*") { _, _, env -> val intf = env.findClass("Intf") val intfT = intf.typeParameters[0] val base = env.findClass("Base") @@ -309,7 +309,7 @@ class ProcessorTests : AbstractProcessorTest() { fun testDispose() { var savedEnv: ProcessingEnvironment? = null - test("AsMemberOf", "*") { set, roundEnv, env -> + test("AsMemberOf", "*") { _, _, env -> savedEnv = env } @@ -333,7 +333,7 @@ class ProcessorTests : AbstractProcessorTest() { test { filer } fun testDisposable(name: String) { - test { (javaClass.methods.first { it.name.startsWith("$name$") }.invoke(this) as DisposableRef<*>).invoke() } + test { (this::class.java.methods.first { it.name.startsWith("$name$") }.invoke(this) as DisposableRef<*>).invoke() } } testDisposable("getProject") @@ -342,7 +342,7 @@ class ProcessorTests : AbstractProcessorTest() { } } - fun testMapMutableMap() = test("MapMutableMap", "*") { set, roundEnv, env -> + fun testMapMutableMap() = test("MapMutableMap", "*") { _, _, env -> val test = env.findClass("Test") fun test(name: String, expected: String) { assertEquals(expected, test.findMethods(name).single().parameters.single().asType().toString()) @@ -359,7 +359,7 @@ class ProcessorTests : AbstractProcessorTest() { var kotlinEnv: KotlinProcessingEnvironment? = null try { - test("MapMutableMap", "*") { set, roundEnv, env -> + test("MapMutableMap", "*") { _, _, env -> kotlinEnv = env as KotlinProcessingEnvironment throw HiThere() } diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt index 50b9ac78c90..34ab87ebca1 100644 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt +++ b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt @@ -87,7 +87,7 @@ class KotlinUastLanguagePlugin : UastLanguagePlugin { val resultingDescriptor = resolvedCall.resultingDescriptor if (resultingDescriptor !is FunctionDescriptor || resultingDescriptor.name.asString() != methodName) return null - val parent = element.parent ?: return null + val parent = element.parent val parentUElement = convertElementWithParent(parent, null) ?: return null val uExpression = KotlinUFunctionCallExpression(element, parentUElement, resolvedCall) diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiParameter.kt b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiParameter.kt index 0774cec052f..8c7f742783f 100644 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiParameter.kt +++ b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiParameter.kt @@ -46,7 +46,7 @@ class UastKotlinPsiParameter( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return ktParameter == (other as? UastKotlinPsiParameter)?.ktParameter } diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt index 2ed4a1ff0a8..2a574725f59 100644 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt +++ b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/psi/UastKotlinPsiVariable.kt @@ -32,7 +32,7 @@ class UastKotlinPsiVariable( override fun equals(other: Any?): Boolean { if (this === other) return true - if (other?.javaClass != javaClass) return false + if (other == null || other::class.java != this::class.java) return false return ktElement == (other as? UastKotlinPsiVariable)?.ktElement } diff --git a/plugins/uast-kotlin/tests/KotlinUastApiTest.kt b/plugins/uast-kotlin/tests/KotlinUastApiTest.kt index 4f1b8546ba4..f924540448d 100644 --- a/plugins/uast-kotlin/tests/KotlinUastApiTest.kt +++ b/plugins/uast-kotlin/tests/KotlinUastApiTest.kt @@ -15,7 +15,7 @@ class KotlinUastApiTest : AbstractKotlinUastTest() { } @Test fun testAnnotationParameters() { - doTest("AnnotationParameters") { name, file -> + doTest("AnnotationParameters") { _, file -> val annotation = file.findElementByText("@IntRange(from = 10, to = 0)") assertEquals(annotation.findAttributeValue("from")?.evaluate(), 10) assertEquals(annotation.findAttributeValue("to")?.evaluate(), 0) @@ -23,7 +23,7 @@ class KotlinUastApiTest : AbstractKotlinUastTest() { } @Test fun testConvertStringTemplate() { - doTest("StringTemplateInClass") { name, file -> + doTest("StringTemplateInClass") { _, file -> val literalExpression = file.findElementByText("lorem") val psi = literalExpression.psi!! Assert.assertTrue(psi is KtLiteralStringTemplateEntry)