Migrate kotlin sources, maven projects and stdlib to new lambda syntax

This commit is contained in:
Stanislav Erokhin
2015-04-01 16:36:44 +03:00
parent e0988de707
commit b703f59e04
74 changed files with 136 additions and 140 deletions
@@ -96,7 +96,7 @@ public abstract class CoveringTryCatchNodeProcessor<T: IntervalWithHandler>() {
}
public fun sortTryCatchBlocks() {
val comp = Comparator {(t1: T, t2: T): Int ->
val comp = Comparator { t1: T, t2: T ->
var result = instructionIndex(t1.handler) - instructionIndex(t2.handler)
if (result == 0) {
result = instructionIndex(t1.startLabel) - instructionIndex(t2.startLabel)
@@ -44,7 +44,7 @@ public class SMAPBuilder(val source: String,
return null;
}
val fileIds = "*F" + realMappings.mapIndexed {(id, file) -> "\n${file.toSMAPFile(id + 1)}" }.join("")
val fileIds = "*F" + realMappings.mapIndexed { id, file -> "\n${file.toSMAPFile(id + 1)}" }.join("")
val lineMappings = "*L" + realMappings.map { it.toSMAPMapping() }.join("")
return "$header\n$fileIds\n$lineMappings\n*E\n"
@@ -72,7 +72,7 @@ public open class NestedSourceMapper(parent: SourceMapper, val ranges: List<Rang
override fun visitLineNumber(iv: MethodVisitor, lineNumber: Int, start: Label) {
val index = Collections.binarySearch(ranges, RangeMapping(lineNumber, lineNumber, 1)) {
(value, key) ->
value, key ->
if (value.contains(key.dest)) 0 else RangeMapping.Comparator.compare(value, key)
}
if (index < 0) {
@@ -107,7 +107,7 @@ public open class InlineLambdaSourceMapper(parent: SourceMapper, smap: SMAPAndMe
override fun visitLineNumber(iv: MethodVisitor, lineNumber: Int, start: Label) {
val index = Collections.binarySearch(ranges, RangeMapping(lineNumber, lineNumber, 1)) {
(value, key) ->
value, key ->
if (value.contains(key.dest)) 0 else RangeMapping.Comparator.compare(value, key)
}
if (index >= 0) {
@@ -31,7 +31,7 @@ class SMAPAndMethodNode(val node: MethodNode, val classSMAP: SMAP) {
val lineNumbers =
InsnStream(node.instructions.getFirst(), null).stream().filterIsInstance<LineNumberNode>().map {
val index = Collections.binarySearch(classSMAP.intervals, RangeMapping(it.line, it.line, 1)) {
(value, key) ->
value, key ->
if (value.contains(key.dest)) 0 else RangeMapping.Comparator.compare(value, key)
}
if (index < 0)
@@ -33,7 +33,7 @@ public fun OutputFileCollection.writeAll(outputDir: File, report: (sources: List
}
}
private val REPORT_NOTHING = { (sources: List<File>, output: File) -> }
private val REPORT_NOTHING = { sources: List<File>, output: File -> }
public fun OutputFileCollection.writeAllTo(outputDir: File) {
writeAll(outputDir, REPORT_NOTHING)
@@ -43,7 +43,7 @@ public class PseudocodeVariableDataCollector(
//see KT-4605
instructionDataMergeStrategy as
(Instruction, Collection<Map<VariableDescriptor, D>>) -> Edges<Map<VariableDescriptor, D>>,
{ (from, to, data) -> filterOutVariablesOutOfScope(from, to, data)},
{ from, to, data -> filterOutVariablesOutOfScope(from, to, data)},
Collections.emptyMap<VariableDescriptor, D>())
//see KT-4605
return result as MutableMap<Instruction, Edges<MutableMap<VariableDescriptor, D>>>
@@ -84,4 +84,4 @@ fun JetType.getSubtypesPredicate(): TypePredicate {
private fun JetType.render(): String = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(this)
public fun <T> TypePredicate.expectedTypeFor(keys: Iterable<T>): Map<T, TypePredicate> =
keys.fold(SmartFMap.emptyMap<T, TypePredicate>()) { (map, key) -> map.plus(key, this) }
keys.fold(SmartFMap.emptyMap<T, TypePredicate>()) { map, key -> map.plus(key, this) }
@@ -49,7 +49,7 @@ public object Renderers {
private val LOG = Logger.getInstance(javaClass<Renderers>())
public val TO_STRING: Renderer<Any> = Renderer {
(element) ->
element ->
if (element is DeclarationDescriptor) {
LOG.warn("Diagnostic renderer TO_STRING was used to render an instance of DeclarationDescriptor.\n"
+ "This is usually a bad idea, because descriptors' toString() includes some debug information, "
@@ -67,7 +67,7 @@ public object Renderers {
public val DECLARATION_NAME: Renderer<JetNamedDeclaration> = Renderer { it.getNameAsSafeName().asString() }
public val RENDER_CLASS_OR_OBJECT: Renderer<JetClassOrObject> = Renderer {
(classOrObject: JetClassOrObject) ->
classOrObject: JetClassOrObject ->
val name = if (classOrObject.getName() != null) " '" + classOrObject.getName() + "'" else ""
if (classOrObject is JetClass) "Class" + name else "Object" + name
}
@@ -77,7 +77,7 @@ public object Renderers {
public val RENDER_TYPE: Renderer<JetType> = Renderer { DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(it) }
public val RENDER_POSITION_VARIANCE: Renderer<Variance> = Renderer {
(variance: Variance) ->
variance: Variance ->
when (variance) {
Variance.INVARIANT -> "invariant"
Variance.IN_VARIANCE -> "in"
@@ -86,7 +86,7 @@ public object Renderers {
}
public val AMBIGUOUS_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
(argument: Collection<ResolvedCall<*>>) ->
argument: Collection<ResolvedCall<*>> ->
val stringBuilder = StringBuilder("\n")
for (call in argument) {
stringBuilder.append(DescriptorRenderer.FQ_NAMES_IN_TYPES.render(call.getResultingDescriptor())).append("\n")
@@ -356,7 +356,7 @@ public object Renderers {
public val RENDER_CONSTRAINT_SYSTEM: Renderer<ConstraintSystem> = Renderer { renderConstraintSystem(it) }
private fun renderTypeBounds(typeBounds: TypeBounds): String {
val renderBound = { (bound: Bound) ->
val renderBound = { bound: Bound ->
val arrow = if (bound.kind == LOWER_BOUND) ">: " else if (bound.kind == UPPER_BOUND) "<: " else ":= "
arrow + RENDER_TYPE.render(bound.constrainingType) + '(' + bound.position + ')'
}
@@ -368,13 +368,13 @@ public fun JetExpression.isFunctionLiteralOutsideParentheses(): Boolean {
}
public fun PsiElement.siblings(forward: Boolean = true, withItself: Boolean = true): Stream<PsiElement> {
val stepFun = if (forward) { (e: PsiElement) -> e.getNextSibling() } else { (e: PsiElement) -> e.getPrevSibling() }
val stepFun = if (forward) { e: PsiElement -> e.getNextSibling() } else { e: PsiElement -> e.getPrevSibling() }
val stream = stream(this, stepFun)
return if (withItself) stream else stream.drop(1)
}
public fun ASTNode.siblings(forward: Boolean = true, withItself: Boolean = true): Stream<ASTNode> {
val stepFun = if (forward) { (node: ASTNode) -> node.getTreeNext() } else { (e: ASTNode) -> e.getTreeNext() }
val stepFun = if (forward) { node: ASTNode -> node.getTreeNext() } else { e: ASTNode -> e.getTreeNext() }
val stream = stream(this, stepFun)
return if (withItself) stream else stream.drop(1)
}
@@ -72,7 +72,7 @@ object DescriptorEquivalenceForOverrides {
if (!ownersEquivalent(a, b, {x, y -> false})) return false
val overridingUtil = OverridingUtil.createWithEqualityAxioms @eq {
(c1, c2): Boolean ->
c1, c2 ->
if (c1 == c2) return@eq true
val d1 = c1.getDeclarationDescriptor()
@@ -81,7 +81,7 @@ private class ExplicitTypeBinding(
jetType.isError() || !sizeIsEqual
}
return psiTypeArguments.indices.map { (index: Int): TypeArgumentBinding<JetTypeElement>? ->
return psiTypeArguments.indices.map { index: Int ->
// todo fix for List<*>
val jetTypeReference = psiTypeArguments[index]
val jetTypeElement = jetTypeReference?.getTypeElement()
@@ -53,7 +53,7 @@ public class LazyAnnotations(
override fun isEmpty() = annotationEntries.isEmpty()
private val annotation = c.storageManager.createMemoizedFunction {
(entry: JetAnnotationEntry) ->
entry: JetAnnotationEntry ->
LazyAnnotationDescriptor(c, entry)
}
@@ -79,7 +79,7 @@ public class LoggingStorageManager(
}
val containingField = if (outerInstance == null) null
else outerClass?.getAllDeclaredFields()?.firstOrNull {
(field): Boolean ->
field ->
field.setAccessible(true)
val value = field.get(outerInstance)
if (value == null) return@firstOrNull false
@@ -146,7 +146,7 @@ public class CapturedTypeApproximationTest() : JetLiteFixture() {
addRandomVariants("00200", "22213", "12114", "20304", "34014", "41333", "11214", "02004", "43244", "03004")
addRandomVariants("021022", "124230", "210030", "202344", "043234", "024400", "102121", "423143", "132121", "233001")
return variants.map { it.fold("#T#") {(type, index) -> type.replace("#T#", typePatterns[index]) } }
return variants.map { it.fold("#T#") { type, index -> type.replace("#T#", typePatterns[index]) } }
}
private fun getTestTypesForTwoTypeVariables(): List<String> {
@@ -119,11 +119,11 @@ public object LibraryUtils {
for (lib in libs) {
when {
lib.isDirectory() ->
traverseDirectory(lib) { (file, path) ->
traverseDirectory(lib) { file, path ->
files.add(FileUtil.loadFile(file))
}
FileUtil.isJarOrZip(lib) ->
traverseArchive(lib) { (content, path) ->
traverseArchive(lib) { content, path ->
files.add(content)
}
lib.getName().endsWith(KotlinJavascriptMetadataUtils.JS_EXT) ->
@@ -44,7 +44,7 @@ public class LazyJavaPackageFragmentProvider(
}
private val topLevelClasses = c.storageManager.createMemoizedFunctionWithNullableValues @lambda {
(jClass: JavaClass): LazyJavaClassDescriptor? ->
jClass: JavaClass ->
val fqName = jClass.getFqName()
if (fqName == null) return@lambda null
@@ -30,7 +30,7 @@ class LazyJavaAnnotations(
private val extraLookup: (FqName) -> JavaAnnotation? = { null }
) : Annotations {
private val annotationDescriptors = c.storageManager.createMemoizedFunctionWithNullableValues {
(annotation: JavaAnnotation) ->
annotation: JavaAnnotation ->
c.resolveAnnotation(annotation)
}
@@ -57,7 +57,7 @@ class LazyJavaAnnotationDescriptor(
javaAnnotation.getClassId()?.asSingleFqName()
}
private val type = c.storageManager.createLazyValue {(): JetType ->
private val type = c.storageManager.createLazyValue {
val fqName = fqName()
if (fqName == null) return@createLazyValue ErrorUtils.createErrorType("No fqName: $javaAnnotation")
val annotationClass = JavaToKotlinClassMap.INSTANCE.mapKotlinClass(fqName, TypeUsage.MEMBER_SIGNATURE_INVARIANT)
@@ -208,7 +208,7 @@ public class LazyJavaClassMemberScope(
}
private val nestedClasses = c.storageManager.createMemoizedFunctionWithNullableValues {
(name: Name) ->
name: Name ->
val jNestedClass = nestedClassIndex()[name]
if (jNestedClass == null) {
val field = enumEntryIndex()[name]
@@ -73,9 +73,8 @@ public abstract class LazyJavaMemberScope(
protected abstract fun getDispatchReceiverParameter(): ReceiverParameterDescriptor?
private val functions = c.storageManager.createMemoizedFunction {
(name: Name): Collection<FunctionDescriptor>
->
private val functions = c.storageManager.createMemoizedFunction<Name, List<FunctionDescriptor>> {
name ->
val result = LinkedHashSet<SimpleFunctionDescriptor>()
for (method in memberIndex().findMethodsByName(name)) {
@@ -222,7 +221,7 @@ public abstract class LazyJavaMemberScope(
protected abstract fun getPropertyNames(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<Name>
private val properties = c.storageManager.createMemoizedFunction {
(name: Name) ->
name: Name ->
val properties = ArrayList<PropertyDescriptor>()
val field = memberIndex().findFieldByName(name)
@@ -40,7 +40,7 @@ object EMPTY_MEMBER_INDEX : MemberIndex {
open class ClassMemberIndex(val jClass: JavaClass, val memberFilter: (JavaMember) -> Boolean) : MemberIndex {
private val methodFilter = {
(m: JavaMethod) ->
m: JavaMethod ->
memberFilter(m) && !DescriptorResolverUtils.isObjectMethodInInterface(m)
}
@@ -65,7 +65,7 @@ class LazyJavaTypeResolver(
}
public fun transformArrayType(arrayType: JavaArrayType, attr: JavaTypeAttributes, isVararg: Boolean = false): JetType {
return run { (): JetType ->
return run {
val javaComponentType = arrayType.getComponentType()
if (javaComponentType is JavaPrimitiveType) {
val jetType = JavaToKotlinClassMap.INSTANCE.mapPrimitiveKotlinClass("[" + javaComponentType.getCanonicalText())
@@ -248,7 +248,6 @@ class LazyJavaTypeResolver(
}
private val nullable = c.storageManager.createLazyValue @l {
(): Boolean ->
when (attr.flexibility) {
FLEXIBLE_LOWER_BOUND -> return@l false
FLEXIBLE_UPPER_BOUND -> return@l true
@@ -39,12 +39,12 @@ abstract class DescriptorBasedProperty(computeDescriptor: () -> PropertyDescript
protected val descriptor: PropertyDescriptor by ReflectProperties.lazySoft(computeDescriptor)
// null if this is a property declared in a foreign (Java) class
private val protoData: PropertyProtoData? by ReflectProperties.lazyWeak @p {(): PropertyProtoData? ->
private val protoData: PropertyProtoData? by ReflectProperties.lazyWeak {
val property = DescriptorUtils.unwrapFakeOverride(descriptor) as? DeserializedPropertyDescriptor
if (property != null) {
val proto = property.proto
if (proto.hasExtension(JvmProtoBuf.propertySignature)) {
return@p PropertyProtoData(proto, property.nameResolver, proto.getExtension(JvmProtoBuf.propertySignature))
return@lazyWeak PropertyProtoData(proto, property.nameResolver, proto.getExtension(JvmProtoBuf.propertySignature))
}
}
null
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.renderer.KeywordStringsGenerated
import com.google.dart.compiler.backend.js.ast.JsFunctionScope
import org.jetbrains.kotlin.generators.di.GeneratorsFileUtil.writeFileIfContentChanged
val commonCases: CaseBuilder.(String, String) -> Unit = { (testByName, testByRef) ->
val commonCases: CaseBuilder.(String, String) -> Unit = { testByName, testByRef ->
case("val", "val $KEYWORD_MARKER: Int", " = 0", testByName)
case("var", "var $KEYWORD_MARKER: Int", " = 0", testByName)
case("fun", "fun $KEYWORD_MARKER()", " { $KEYWORD_MARKER() }", testByRef)
@@ -156,7 +156,7 @@ private class PerFileAnalysisCache(val file: JetFile, val resolveSession: Resolv
val analyzableParent = KotlinResolveDataProvider.findAnalyzableParent(element)
return synchronized(this) { (): AnalysisResult ->
return synchronized<AnalysisResult>(this) {
val cached = lookUp(analyzableParent)
if (cached != null) return@synchronized cached
@@ -53,12 +53,12 @@ fun createModuleResolverProvider(
val modulesToCreateResolversFor = allModuleInfos.filter(moduleFilter)
fun createResolverForProject(): ResolverForProject<IdeaModuleInfo, ResolverForModule> {
val modulesContent = {(module: IdeaModuleInfo) ->
val modulesContent = { module: IdeaModuleInfo ->
ModuleContent(syntheticFilesByModule[module] ?: listOf(), module.contentScope())
}
val jvmPlatformParameters = JvmPlatformParameters {
(javaClass: JavaClass) ->
javaClass: JavaClass ->
val psiClass = (javaClass as JavaClassImpl).getPsi()
psiClass.getModuleInfo()
}
@@ -40,7 +40,7 @@ class ModuleTypeCacheManager private (project: Project) {
private val cachedValue = CachedValuesManager.getManager(project).createParameterizedCachedValue(
{
(module: Module?) ->
module: Module? ->
val moduleType = if (module != null) computeType(module) else null
CachedValueProvider.Result.create<ModuleType>(moduleType, vfsModificationTracker)
}, false)
@@ -49,7 +49,7 @@ public fun HierarchySearchRequest<PsiElement>.searchOverriders(): Query<PsiMetho
return psiMethods
.map { psiMethod -> KotlinPsiMethodOverridersSearch.search(copy(psiMethod)) }
.reduce {(query1, query2) -> MergeQuery(query1, query2)}
.reduce { query1, query2 -> MergeQuery(query1, query2)}
}
public object KotlinPsiMethodOverridersSearch : HierarchySearch<PsiMethod>(PsiMethodOverridingHierarchyTraverser) {
@@ -167,7 +167,7 @@ private fun processClassDelegationCallsToSpecifiedConstructor(
// Check if reference resolves to extension function whose receiver is the same as declaration's parent (or its superclass)
// Used in extension search
fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: JetNamedDeclaration): Boolean =
checkUsageVsOriginalDescriptor(declaration) { (usageDescriptor, targetDescriptor) ->
checkUsageVsOriginalDescriptor(declaration) { usageDescriptor, targetDescriptor ->
when {
usageDescriptor == targetDescriptor -> false
usageDescriptor !is FunctionDescriptor -> false
@@ -187,17 +187,17 @@ fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: JetNamedDeclara
// Check if reference resolves to the declaration with the same parent
// Used in overload search
fun PsiReference.isUsageInContainingDeclaration(declaration: JetNamedDeclaration): Boolean =
checkUsageVsOriginalDescriptor(declaration) { (usageDescriptor, targetDescriptor) ->
checkUsageVsOriginalDescriptor(declaration) { usageDescriptor, targetDescriptor ->
usageDescriptor != targetDescriptor
&& usageDescriptor.getContainingDeclaration() == targetDescriptor.getContainingDeclaration()
}
fun PsiReference.isCallableOverrideUsage(declaration: JetNamedDeclaration): Boolean {
val decl2Desc = {(declaration: JetDeclaration) ->
val decl2Desc = { declaration: JetDeclaration ->
if (declaration is JetParameter && declaration.hasValOrVarNode()) declaration.propertyDescriptor else declaration.descriptor
}
return checkUsageVsOriginalDescriptor(declaration, decl2Desc) { (usageDescriptor, targetDescriptor) ->
return checkUsageVsOriginalDescriptor(declaration, decl2Desc) { usageDescriptor, targetDescriptor ->
usageDescriptor is CallableDescriptor && targetDescriptor is CallableDescriptor
&& OverrideResolver.overrides(usageDescriptor, targetDescriptor)
}
@@ -56,7 +56,7 @@ public object ProjectRootsUtil {
includeLibrarySource: Boolean,
includeLibraryClasses: Boolean
): Boolean {
return runReadAction {(): Boolean ->
return runReadAction {
val virtualFile = when (element) {
is PsiDirectory -> element.getVirtualFile()
else -> element.getContainingFile()?.getVirtualFile()
@@ -100,7 +100,7 @@ fun rethrowWithCancelIndicator(exception: ProcessCanceledException): ProcessCanc
return exception
}
fun PrefixMatcher.asNameFilter() = { (name: Name) ->
fun PrefixMatcher.asNameFilter() = { name: Name ->
if (name.isSpecial()) {
false
}
@@ -48,7 +48,7 @@ object KeywordValues {
}
if (!skipTrueFalse) {
val booleanInfoClassifier = { (info: ExpectedInfo) ->
val booleanInfoClassifier = { info: ExpectedInfo ->
if (info.type == KotlinBuiltIns.getInstance().getBooleanType()) ExpectedInfoClassification.matches(TypeSubstitutor.EMPTY) else ExpectedInfoClassification.notMatches
}
collection.addLookupElements(null, expectedInfos, booleanInfoClassifier, { LookupElementBuilder.create("true").bold().assignSmartCompletionPriority(SmartCompletionItemPriority.TRUE) })
@@ -45,7 +45,7 @@ object LambdaItems {
for (functionType in distinctTypes) {
val lookupString = buildLambdaPresentation(functionType)
val lookupElement = LookupElementBuilder.create(lookupString)
.withInsertHandler({ (context, lookupElement) ->
.withInsertHandler({ context, lookupElement ->
val offset = context.getStartOffset()
val placeholder = "{}"
context.getDocument().replaceString(offset, context.getTailOffset(), placeholder)
@@ -76,7 +76,7 @@ class MultipleArgumentsItemProvider(val bindingContext: BindingContext,
return LookupElementBuilder
.create(variables.map { IdeDescriptorRenderers.SOURCE_CODE.renderName(it.getName()) }.joinToString(", "))
.withInsertHandler { (context, lookupElement) ->
.withInsertHandler { context, lookupElement ->
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
val offset = context.getOffsetMap().getOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET)
if (offset != -1) {
@@ -146,7 +146,7 @@ class SmartCompletion(
val result = ArrayList<LookupElement>()
val types = descriptor.fuzzyTypes(smartCastTypes)
val infoClassifier = { (expectedInfo: ExpectedInfo) -> types.classifyExpectedInfo(expectedInfo) }
val infoClassifier = { expectedInfo: ExpectedInfo -> types.classifyExpectedInfo(expectedInfo) }
result.addLookupElements(descriptor, expectedInfos, infoClassifier) { descriptor ->
lookupElementFactory.createLookupElement(descriptor, resolutionFacade, bindingContext, true)
@@ -199,7 +199,7 @@ class SmartCompletion(
if (shouldCompleteThisItems(prefixMatcher)) {
val items = thisExpressionItems(bindingContext, place, prefixMatcher.getPrefix())
for ((factory, type) in items) {
val classifier = { (expectedInfo: ExpectedInfo) -> type.classifyExpectedInfo(expectedInfo) }
val classifier = { expectedInfo: ExpectedInfo -> type.classifyExpectedInfo(expectedInfo) }
addLookupElements(null, expectedInfos, classifier) {
factory().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS)
}
@@ -158,7 +158,7 @@ class TypeInstantiationItems(
itemText = "object: " + itemText + "{...}"
lookupString = "object"
allLookupStrings = setOf(lookupString, lookupElement.getLookupString())
insertHandler = InsertHandler<LookupElement> {(context, item) ->
insertHandler = InsertHandler<LookupElement> { context, item ->
val editor = context.getEditor()
val startOffset = context.getStartOffset()
val text = "object: $typeText$constructorParenthesis {}"
@@ -499,7 +499,7 @@ public fun createJavaMethod(template: PsiMethod, targetClass: PsiClass): PsiMeth
copyModifierListItems(template.getModifierList(), method.getModifierList())
copyTypeParameters(template, method) { (method, typeParameterList) ->
copyTypeParameters(template, method) { method, typeParameterList ->
method.addAfter(typeParameterList, method.getModifierList())
}
@@ -566,7 +566,7 @@ fun createJavaClass(klass: JetClass, targetClass: PsiClass): PsiMember {
javaClass.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false)
}
copyTypeParameters(template, javaClass) { (klass, typeParameterList) ->
copyTypeParameters(template, javaClass) { klass, typeParameterList ->
klass.addAfter(typeParameterList, klass.getNameIdentifier())
}
@@ -70,10 +70,10 @@ public class CheckPartialBodyResolveAction : AnAction() {
progressIndicator?.setText("Checking resolve $i of ${files.size()}...")
progressIndicator?.setText2(file.getVirtualFile().getPath())
val partialResolveDump = dumpResolve(file) {(element, resolutionFacade) ->
val partialResolveDump = dumpResolve(file) { element, resolutionFacade ->
resolutionFacade.analyze(element, BodyResolveMode.PARTIAL)
}
val goldDump = dumpResolve(file) {(element, resolutionFacade) ->
val goldDump = dumpResolve(file) { element, resolutionFacade ->
resolutionFacade.analyze(element)
}
if (partialResolveDump != goldDump) {
@@ -214,7 +214,7 @@ public class JetPositionManager(private val myDebugProcess: DebugProcess) : Mult
var value: CachedValue<JetTypeMapper>? = myTypeMappers.get(key)
if (value == null) {
value = CachedValuesManager.getManager(file.getProject()).createCachedValue<JetTypeMapper>(
{() ->
{
val typeMapper = createTypeMapper(file)
CachedValueProvider.Result<JetTypeMapper>(typeMapper, PsiModificationTracker.MODIFICATION_COUNT)
}, false)
@@ -268,7 +268,7 @@ public class JetPositionManager(private val myDebugProcess: DebugProcess) : Mult
TestOnly
public fun addTypeMapper(file: JetFile, typeMapper: JetTypeMapper) {
val value = CachedValuesManager.getManager(file.getProject()).createCachedValue<JetTypeMapper>(
{ () -> CachedValueProvider.Result<JetTypeMapper>(typeMapper, PsiModificationTracker.MODIFICATION_COUNT) }, false)
{ CachedValueProvider.Result<JetTypeMapper>(typeMapper, PsiModificationTracker.MODIFICATION_COUNT) }, false)
val key = createKeyForTypeMapper(file)
myTypeMappers.put(key, value)
}
@@ -47,7 +47,7 @@ class KotlinCodeFragmentFactory: CodeFragmentFactory() {
}
codeFragment.putCopyableUserData(JetCodeFragment.RUNTIME_TYPE_EVALUATOR, {
(expression: JetExpression): JetType? ->
expression: JetExpression ->
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).getContext()
val debuggerSession = debuggerContext.getDebuggerSession()
@@ -53,8 +53,7 @@ class KotlinEvaluateExpressionCache(val project: Project) {
): CompiledDataDescriptor {
val evaluateExpressionCache = getInstance(codeFragment.getProject())
return synchronized(evaluateExpressionCache.cachedCompiledData) {
(): CompiledDataDescriptor ->
return synchronized<CompiledDataDescriptor>(evaluateExpressionCache.cachedCompiledData) {
val cache = evaluateExpressionCache.cachedCompiledData.getValue()!!
val text = "${codeFragment.importsToString()}\n${codeFragment.getText()}"
@@ -73,7 +72,7 @@ class KotlinEvaluateExpressionCache(val project: Project) {
}
private fun canBeEvaluatedInThisContext(compiledData: CompiledDataDescriptor, context: EvaluationContextImpl): Boolean {
return compiledData.parameters.all { (p): Boolean ->
return compiledData.parameters.all { p ->
val (name, jetType) = p
val value = context.findLocalVariable(name, asmType = null, checkType = false, failIfNotFound = false)
if (value == null) return@all false
@@ -69,7 +69,6 @@ private fun defineClasses(
private object FunctionImplBytes {
val bytes: ByteArray by Delegates.lazy {
(): ByteArray ->
val inputStream = this.javaClass.getClassLoader().getResourceAsStream("kotlin/jvm/internal/FunctionImpl.class")
if (inputStream != null) {
try {
@@ -81,7 +81,7 @@ class KotlinSpacingBuilder(val codeStyleSettings: CodeStyleSettings) {
}
fun emptyLinesIfLineBreakInLeft(emptyLines: Int, numberOfLineFeedsOtherwise: Int = 1, numSpacesOtherwise: Int = 0) {
newRule {(parent: ASTBlock, left: ASTBlock, right: ASTBlock) ->
newRule { parent: ASTBlock, left: ASTBlock, right: ASTBlock ->
val dependentSpacingRule = DependentSpacingRule(Trigger.HAS_LINE_FEEDS).registerData(Anchor.MIN_LINE_FEEDS, emptyLines + 1)
LineFeedDependantSpacing(
numSpacesOtherwise, numSpacesOtherwise,
@@ -93,7 +93,7 @@ class KotlinSpacingBuilder(val codeStyleSettings: CodeStyleSettings) {
}
fun spacing(spacing: Spacing) {
newRule { (parent, left, right) -> spacing }
newRule { parent, left, right -> spacing }
}
fun customRule(block: (parent: ASTBlock, left: ASTBlock, right: ASTBlock) -> Spacing?) {
@@ -63,7 +63,7 @@ fun createSpacingBuilder(settings: CodeStyleSettings): KotlinSpacingBuilder {
emptyLines = 0, numSpacesOtherwise = 1, numberOfLineFeedsOtherwise = 0)
val parameterWithDocCommentRule = {
(parent: ASTBlock, left: ASTBlock, right: ASTBlock) ->
parent: ASTBlock, left: ASTBlock, right: ASTBlock ->
if (right.getNode().getFirstChildNode().getElementType() == JetTokens.DOC_COMMENT) {
Spacing.createSpacing(0, 0, 1, true, settings.KEEP_BLANK_LINES_IN_DECLARATIONS)
}
@@ -248,12 +248,12 @@ fun createSpacingBuilder(settings: CodeStyleSettings): KotlinSpacingBuilder {
}
fun leftBraceRule(blockType: IElementType = BLOCK) = {
(parent: ASTBlock, left: ASTBlock, right: ASTBlock) ->
parent: ASTBlock, left: ASTBlock, right: ASTBlock ->
spacingForLeftBrace(right.getNode(), blockType)
}
val leftBraceRuleIfBlockIsWrapped = {
(parent: ASTBlock, left: ASTBlock, right: ASTBlock) ->
parent: ASTBlock, left: ASTBlock, right: ASTBlock ->
spacingForLeftBrace(right.getNode()!!.getFirstChildNode())
}
@@ -41,6 +41,6 @@ class KotlinOverrideTreeStructure(project: Project, val element: PsiElement) : H
return javaTreeStructures
.stream()
.map (::buildChildrenByTreeStructure)
.reduce { (a, b) -> ContainerUtil.union(a.toSet(), b.toSet()).copyToArray() }
.reduce { a, b -> ContainerUtil.union(a.toSet(), b.toSet()).copyToArray() }
}
}
@@ -47,7 +47,7 @@ fun getOverriddenPropertyTooltip(property: JetProperty): String? {
val consumer = AdapterProcessor<PsiMethod, PsiClass>(
CommonProcessors.UniqueProcessor<PsiClass>(PsiElementProcessorAdapter(overriddenInClassesProcessor)),
Function { (method: PsiMethod?): PsiClass? -> method?.getContainingClass() }
Function { method: PsiMethod? -> method?.getContainingClass() }
)
for (method in LightClassUtil.getLightClassPropertyMethods(property)) {
@@ -117,7 +117,7 @@ object KDocRenderer {
public fun MarkdownNode.toHtml(): String {
val sb = StringBuilder()
visit {(node, processChildren) ->
visit { node, processChildren ->
val nodeType = node.type
val nodeText = node.text
when (nodeType) {
@@ -76,14 +76,14 @@ public class ExtractKotlinFunctionHandler(
EXTRACT_FUNCTION,
editor,
file,
{(elements, parent) -> parent.getExtractionContainers(elements.size() == 1, allContainersEnabled) },
{ elements, parent -> parent.getExtractionContainers(elements.size() == 1, allContainersEnabled) },
continuation
)
}
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
if (file !is JetFile) return
selectElements(editor, file) { (elements, targetSibling) -> doInvoke(editor, file, elements, targetSibling) }
selectElements(editor, file) { elements, targetSibling -> doInvoke(editor, file, elements, targetSibling) }
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
@@ -435,7 +435,7 @@ fun TypeParameter.collectReferencedTypes(bindingContext: BindingContext): List<J
}
private fun JetType.isExtractable(targetScope: JetScope?): Boolean {
return collectReferencedTypes(true).fold(true) { (extractable, typeToCheck) ->
return collectReferencedTypes(true).fold(true) { extractable, typeToCheck ->
val parameterTypeDescriptor = typeToCheck.getConstructor().getDeclarationDescriptor() as? TypeParameterDescriptor
val typeParameter = parameterTypeDescriptor?.let {
DescriptorToSourceUtils.descriptorToDeclaration(it)
@@ -452,7 +452,7 @@ private fun JetType.processTypeIfExtractable(
targetScope: JetScope?,
processTypeArguments: Boolean = true
): Boolean {
return collectReferencedTypes(processTypeArguments).fold(true) { (extractable, typeToCheck) ->
return collectReferencedTypes(processTypeArguments).fold(true) { extractable, typeToCheck ->
val parameterTypeDescriptor = typeToCheck.getConstructor().getDeclarationDescriptor() as? TypeParameterDescriptor
val typeParameter = parameterTypeDescriptor?.let {
DescriptorToSourceUtils.descriptorToDeclaration(it)
@@ -58,10 +58,10 @@ public class KotlinIntroducePropertyHandler(
operationName = INTRODUCE_PROPERTY,
editor = editor,
file = file,
getContainers = {(elements, parent) ->
getContainers = { elements, parent ->
parent.getExtractionContainers(strict = true, includeAll = true).filter { it is JetClassBody || it is JetFile }
}
) { (elements, targetSibling) ->
) { elements, targetSibling ->
val adjustedElements = (elements.singleOrNull() as? JetBlockExpression)?.getStatements() ?: elements
if (adjustedElements.isNotEmpty()) {
val options = ExtractionOptions(extractAsProperty = true)
@@ -105,7 +105,7 @@ public class RenameKotlinPropertyProcessor : RenamePsiElementProcessor() {
val oldGetterName = PropertyCodegen.getterName(element.getNameAsName())
val oldSetterName = PropertyCodegen.setterName(element.getNameAsName())
val refKindUsages = usages.toList().groupBy { (usage: UsageInfo): UsageKind ->
val refKindUsages = usages.toList().groupBy { usage: UsageInfo ->
val refElement = usage.getReference()?.resolve()
if (refElement is PsiMethod) {
when (refElement.getName()) {
@@ -112,7 +112,7 @@ public class KotlinSafeDeleteProcessor : JavaSafeDeleteProcessor() {
elements
.map { element -> findUsagesByJavaProcessor(element, true)?.getInsideDeletedCondition() }
.filterNotNull()
.fold(insideDeleted) {(condition1, condition2) -> Conditions.or(condition1, condition2) }
.fold(insideDeleted) { condition1, condition2 -> Conditions.or(condition1, condition2) }
fun findUsagesByJavaProcessor(jetDeclaration: JetDeclaration): NonCodeUsageSearchInfo {
return NonCodeUsageSearchInfo(
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.psiUtil.siblings
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange.Match
private val SIGNIFICANT_FILTER = { (e: PsiElement) -> e !is PsiWhiteSpace && e !is PsiComment && e.getTextLength() > 0 }
private val SIGNIFICANT_FILTER = { e: PsiElement -> e !is PsiWhiteSpace && e !is PsiComment && e.getTextLength() > 0 }
public trait JetPsiRange {
public object Empty : JetPsiRange {
@@ -225,12 +225,12 @@ public class JetPsiUnifier(
if (args1.size != args2.size) return UNMATCHED
if (rc1.getCall().getValueArguments().size != args1.size || rc2.getCall().getValueArguments().size != args2.size) return null
return (args1.stream() zip args2.stream()).fold(MATCHED) { (s, p) ->
return (args1.stream() zip args2.stream()).fold(MATCHED) { s, p ->
val (arg1, arg2) = p
s and when {
arg1 == arg2 -> MATCHED
arg1 == null || arg2 == null -> UNMATCHED
else -> (arg1.getArguments().stream() zip arg2.getArguments().stream()).fold(MATCHED) { (s, p) ->
else -> (arg1.getArguments().stream() zip arg2.getArguments().stream()).fold(MATCHED) { s, p ->
s and matchArguments(p.first, p.second)
}
}
@@ -737,7 +737,7 @@ public class JetPsiUnifier(
val patternElements = pattern.elements
if (targetElements.size != patternElements.size) return UNMATCHED
return (targetElements.stream() zip patternElements.stream()).fold(MATCHED) {(s, p) ->
return (targetElements.stream() zip patternElements.stream()).fold(MATCHED) { s, p ->
if (s != UNMATCHED) s and doUnify(p.first, p.second) else s
}
}
@@ -54,7 +54,7 @@ public abstract class AbstractKotlinCoverageOutputFilesTest(): JetLightCodeInsig
private fun createEmptyFile(dir: VirtualFile, relativePath: String) {
var currentDir = dir
val segments = relativePath.split('/')
segments.forEachIndexed {(i, s) ->
segments.forEachIndexed { i, s ->
if (i < segments.size() - 1) {
currentDir = currentDir.createChildDirectory(null, s)
} else {
@@ -110,7 +110,7 @@ abstract class KotlinDebuggerTestBase : KotlinDebuggerTestCase() {
}
protected fun SuspendContextImpl.printContext() {
runReadAction {(): Unit ->
runReadAction {
if (this.getFrameProxy() == null) {
return@runReadAction println("Context thread is null", ProcessOutputTypes.SYSTEM)
}
@@ -130,7 +130,7 @@ class AnnotationConverter(private val converter: Converter) {
return componentsConverted
}
else {
val expressionGenerator = { (codeConverter: CodeConverter) ->
val expressionGenerator = { codeConverter: CodeConverter ->
val expectedTypeConverted = converter.typeConverter.convertType(expectedType)
if (expectedTypeConverted is ArrayType) {
val array = createArrayInitializerExpression(expectedTypeConverted, componentsConverted.map { it(codeConverter) }, needExplicitType = false)
@@ -40,14 +40,14 @@ public val JetType.nameIfStandardType: Name?
public fun JetType.getJetTypeFqName(printTypeArguments: Boolean): String {
val declaration = requireNotNull(getConstructor().getDeclarationDescriptor())
if (declaration is TypeParameterDescriptor) {
return StringUtil.join(declaration.getUpperBounds(), { (type) -> type.getJetTypeFqName(printTypeArguments) }, "&")
return StringUtil.join(declaration.getUpperBounds(), { type -> type.getJetTypeFqName(printTypeArguments) }, "&")
}
val typeArguments = getArguments()
val typeArgumentsAsString: String
if (printTypeArguments && !typeArguments.isEmpty()) {
val joinedTypeArguments = StringUtil.join(typeArguments, { (projection) -> projection.getType().getJetTypeFqName(false) }, ", ")
val joinedTypeArguments = StringUtil.join(typeArguments, { projection -> projection.getType().getJetTypeFqName(false) }, ", ")
typeArgumentsAsString = "<" + joinedTypeArguments + ">"
} else {
@@ -57,7 +57,7 @@ public object KotlinJavascriptSerializationUtil {
val packages = getPackages(contentMap)
val load = { (path: String) -> if (!contentMap.containsKey(path)) null else ByteArrayInputStream(contentMap.get(path)) }
val load = { path: String -> if (!contentMap.containsKey(path)) null else ByteArrayInputStream(contentMap.get(path)) }
val providers = arrayListOf<PackageFragmentProvider>()
for (packageName in packages) {
@@ -57,7 +57,7 @@ class JdbcTest {
}
test fun mapIterator() {
val mapper = { (rs : ResultSet) ->
val mapper = { rs: ResultSet ->
"id: ${rs["id"]}"
}
+22 -22
View File
@@ -843,140 +843,140 @@ public fun <T> Stream<T>.plus(stream: Stream<T>): Stream<T> {
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Array<out T>.zip(array: Array<out R>): List<Pair<T, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> BooleanArray.zip(array: Array<out R>): List<Pair<Boolean, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ByteArray.zip(array: Array<out R>): List<Pair<Byte, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> CharArray.zip(array: Array<out R>): List<Pair<Char, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> DoubleArray.zip(array: Array<out R>): List<Pair<Double, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> FloatArray.zip(array: Array<out R>): List<Pair<Float, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> IntArray.zip(array: Array<out R>): List<Pair<Int, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> LongArray.zip(array: Array<out R>): List<Pair<Long, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ShortArray.zip(array: Array<out R>): List<Pair<Short, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Iterable<T>.zip(array: Array<out R>): List<Pair<T, R>> {
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Array<out T>.zip(other: Iterable<R>): List<Pair<T, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> BooleanArray.zip(other: Iterable<R>): List<Pair<Boolean, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ByteArray.zip(other: Iterable<R>): List<Pair<Byte, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> CharArray.zip(other: Iterable<R>): List<Pair<Char, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> DoubleArray.zip(other: Iterable<R>): List<Pair<Double, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> FloatArray.zip(other: Iterable<R>): List<Pair<Float, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> IntArray.zip(other: Iterable<R>): List<Pair<Int, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> LongArray.zip(other: Iterable<R>): List<Pair<Long, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <R> ShortArray.zip(other: Iterable<R>): List<Pair<Short, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
*/
public fun <T, R> Iterable<T>.zip(other: Iterable<R>): List<Pair<T, R>> {
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
}
/**
@@ -997,7 +997,7 @@ public fun String.zip(other: String): List<Pair<Char, Char>> {
* Resulting sequence has length of shortest input sequences.
*/
public fun <T, R> Sequence<T>.zip(sequence: Sequence<R>): Sequence<Pair<T, R>> {
return MergingSequence(this, sequence) { (t1, t2) -> t1 to t2 }
return MergingSequence(this, sequence) { t1, t2 -> t1 to t2 }
}
@@ -1007,6 +1007,6 @@ deprecated("Migrate to using Sequence<T> and respective functions")
* Resulting stream has length of shortest input streams.
*/
public fun <T, R> Stream<T>.zip(stream: Stream<R>): Stream<Pair<T, R>> {
return MergingStream(this, stream) { (t1, t2) -> t1 to t2 }
return MergingStream(this, stream) { t1, t2 -> t1 to t2 }
}
@@ -390,7 +390,7 @@ public fun <T> Iterator<T>.reverse() : List<T> {
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, R: Comparable<R>> Iterator<T>.sortBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) f: (T) -> R) : List<T> {
val sortedList = toCollection(ArrayList<T>())
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) ->
val sortBy: Comparator<T> = comparator<T> {x: T, y: T ->
val xr = f(x)
val yr = f(y)
xr.compareTo(yr)
@@ -76,7 +76,7 @@ public object Delegates {
* @param onChange the callback which is called when the property value is changed.
*/
public fun observable<T>(initial: T, onChange: (desc: PropertyMetadata, oldValue: T, newValue: T) -> Unit): ReadWriteProperty<Any?, T> {
return ObservableProperty<T>(initial) { (desc, old, new) ->
return ObservableProperty<T>(initial) { desc, old, new ->
onChange(desc, old, new)
true
}
@@ -257,7 +257,7 @@ public abstract class MapVar<T, K, V>() : MapVal<T, K, V>(), ReadWriteProperty<T
}
private val defaultKeyProvider:(PropertyMetadata) -> String = {it.name}
private val defaultValueProvider:(Any?, Any?) -> Nothing = {(thisRef, key) -> throw KeyMissingException("$key is missing from $thisRef")}
private val defaultValueProvider:(Any?, Any?) -> Nothing = {thisRef, key -> throw KeyMissingException("$key is missing from $thisRef")}
/**
* Implements a read-only property delegate that stores the property values in a given map instance and uses the given
+1 -1
View File
@@ -35,7 +35,7 @@ class OrderingTest {
}
Test fun sortComparatorThenComparator() {
val comparator = comparator<Item> {(a, b) -> a.name.compareTo(b.name) } thenComparator {(a, b) -> a.rating.compareTo(b.rating) }
val comparator = comparator<Item> { a, b -> a.name.compareTo(b.name) } thenComparator { a, b -> a.rating.compareTo(b.rating) }
val diff = comparator.compare(v1, v2)
assertTrue(diff > 0)
@@ -200,7 +200,7 @@ abstract class IterableTests<T : Iterable<String>>(val data: T, val empty: T) {
Test
fun mapIndexed() {
val shortened = data.mapIndexed {(index, value) -> value.substring(0..index) }
val shortened = data.mapIndexed { index, value -> value.substring(0..index) }
assertEquals(2, shortened.size())
assertEquals(listOf("f", "ba"), shortened)
}
@@ -84,7 +84,7 @@ public class SequenceTest {
}
test fun foldReducesTheFirstNElements() {
val sum = {(a: Int, b: Int) -> a + b }
val sum = { a: Int, b: Int -> a + b }
assertEquals(listOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
}
@@ -93,7 +93,7 @@ public class SequenceTest {
}
test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(listOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile {(i: Int) -> i < 20 }.toList())
assertEquals(listOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList())
}
test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
@@ -36,7 +36,7 @@ class SerializableTest() : TestCase() {
fun testComplexClosure() {
val y = 12
val fn1 = {(x: Int) -> (x + y).toString() }
val fn1 = { x: Int -> (x + y).toString() }
val fn2: Int.(Int) -> String = { fn1(this + it) }
val byteOutputStream = ByteArrayOutputStream()
@@ -8,7 +8,7 @@ class IteratorsJVMTest {
test fun flatMapAndTakeExtractTheTransformedElements() {
fun intToBinaryDigits() = { (i: Int) ->
fun intToBinaryDigits() = { i: Int ->
val binary = Integer.toBinaryString(i)!!
var index = 0
sequence<Char> { if (index < binary.length()) binary.get(index++) else null }
@@ -18,7 +18,7 @@ class IteratorsTest {
}
test fun foldReducesTheFirstNElements() {
val sum = { (a: Int, b: Int) -> a + b }
val sum = { a: Int, b: Int -> a + b }
assertEquals(arrayListOf(13, 21, 34, 55, 89).fold(0, sum), fibonacci().filter { it > 10 }.take(5).fold(0, sum))
}
@@ -27,11 +27,11 @@ class IteratorsTest {
}
test fun mapAndTakeWhileExtractTheTransformedElements() {
assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { (i: Int) -> i < 20 }.toList())
assertEquals(arrayListOf(0, 3, 3, 6, 9, 15), fibonacci().map { it * 3 }.takeWhile { i: Int -> i < 20 }.toList())
}
test fun mapIndexed() {
assertEquals(arrayListOf(0, 1, 2, 6, 12), fibonacci().mapIndexed { index, value -> index * value }.takeWhile {(i: Int) -> i < 20 }.toList())
assertEquals(arrayListOf(0, 1, 2, 6, 12), fibonacci().mapIndexed { index, value -> index * value }.takeWhile { i: Int -> i < 20 }.toList())
}
test fun joinConcatenatesTheFirstNElementsAboveAThreshold() {
@@ -12,7 +12,7 @@ class JavautilCollectionsTest {
val TEST_LIST = array(2, 0, 9, 7, 1).toList()
val SORTED_TEST_LIST = array(0, 1, 2, 7, 9).toList()
val MAX_ELEMENT = 9
val COMPARATOR = comparator { (x: Int, y: Int) -> if (x > y) 1 else if (x < y) -1 else 0 }
val COMPARATOR = comparator { x: Int, y: Int -> if (x > y) 1 else if (x < y) -1 else 0 }
test fun maxWithComparator() {
assertEquals(MAX_ELEMENT, Collections.max(TEST_LIST, COMPARATOR))
@@ -72,7 +72,7 @@ class TestObservablePropertyInChangeSupport: WithBox, ChangeSupport() {
class TestObservableProperty: WithBox {
var result = false
var b by Delegates.observable(1, {(pd, o, n) -> result = true})
var b by Delegates.observable(1, { pd, o, n -> result = true})
override fun box(): String {
b = 4
@@ -86,7 +86,7 @@ class A(val p: Boolean)
class TestVetoableProperty: WithBox {
var result = false
var b by Delegates.vetoable(A(true), {(pd, o, n) -> result = n.p == true; result})
var b by Delegates.vetoable(A(true), { pd, o, n -> result = n.p == true; result})
override fun box(): String {
val firstValue = A(true)
@@ -115,8 +115,8 @@ class TestMapPropertyString(): WithBox {
class TestMapValWithDefault(): WithBox {
val map = hashMapOf<String, String>()
val a: String by Delegates.mapVal(map, default = { ref, desc -> "aDefault" })
val b: String by FixedMapVal(map, default = { (ref: TestMapValWithDefault, desc: String) -> "bDefault" }, key = {"b"})
val c: String by FixedMapVal(map, default = { (ref: TestMapValWithDefault, desc: String) -> "cDefault" }, key = { desc -> desc.name })
val b: String by FixedMapVal(map, default = { ref: TestMapValWithDefault, desc: String -> "bDefault" }, key = {"b"})
val c: String by FixedMapVal(map, default = { ref: TestMapValWithDefault, desc: String -> "cDefault" }, key = { desc -> desc.name })
override fun box(): String {
if (a != "aDefault") return "fail at 'a'"
@@ -129,8 +129,8 @@ class TestMapValWithDefault(): WithBox {
class TestMapVarWithDefault(): WithBox {
val map = hashMapOf<String, Any?>()
var a: String by Delegates.mapVar(map, default = {ref, desc -> "aDefault" })
var b: String by FixedMapVar(map, default = {(ref: Any?, desc: String) -> "bDefault" }, key = {"b"})
var c: String by FixedMapVar(map, default = {(ref: Any?, desc: String) -> "cDefault" }, key = { desc -> desc.name })
var b: String by FixedMapVar(map, default = {ref: Any?, desc: String -> "bDefault" }, key = {"b"})
var c: String by FixedMapVar(map, default = {ref: Any?, desc: String -> "cDefault" }, key = { desc -> desc.name })
override fun box(): String {
if (a != "aDefault") return "fail at 'a'"
+4 -4
View File
@@ -290,7 +290,7 @@ class StringJVMTest {
test fun testReplaceAllClosure() {
val s = "test123zzz"
val result = s.replaceAll("\\d+") { (mr) ->
val result = s.replaceAll("\\d+") { mr ->
"[" + mr.group() + "]"
}
assertEquals("test[123]zzz", result)
@@ -298,7 +298,7 @@ class StringJVMTest {
test fun testReplaceAllClosureAtStart() {
val s = "123zzz"
val result = s.replaceAll("\\d+") { (mr) ->
val result = s.replaceAll("\\d+") { mr ->
"[" + mr.group() + "]"
}
assertEquals("[123]zzz", result)
@@ -306,7 +306,7 @@ class StringJVMTest {
test fun testReplaceAllClosureAtEnd() {
val s = "test123"
val result = s.replaceAll("\\d+") { (mr) ->
val result = s.replaceAll("\\d+") { mr ->
"[" + mr.group() + "]"
}
assertEquals("test[123]", result)
@@ -314,7 +314,7 @@ class StringJVMTest {
test fun testReplaceAllClosureEmpty() {
val s = ""
val result = s.replaceAll("\\d+") { (mr) ->
val result = s.replaceAll("\\d+") { mr ->
"x"
}
assertEquals("", result)
+1 -1
View File
@@ -285,7 +285,7 @@ class StringTest {
)
val trimChars = charArray('-','=')
val trimPredicate = { (it: Char) -> it < '0' || it > '9' } // TODO: Use !it.isDigit when available in JS
val trimPredicate = { it: Char -> it < '0' || it > '9' } // TODO: Use !it.isDigit when available in JS
for (example in examplesForPredicate) {
assertEquals(example.trimStart(*trimChars).trimEnd(*trimChars), example.trim(*trimChars))
assertEquals(example.trimStart(trimPredicate).trimEnd(trimPredicate), example.trim(trimPredicate))
@@ -219,7 +219,7 @@ fun generators(): List<GenericFunction> {
returns("List<Pair<T, R>>")
body {
"""
return merge(other) { (t1, t2) -> t1 to t2 }
return merge(other) { t1, t2 -> t1 to t2 }
"""
}
}
@@ -256,7 +256,7 @@ fun generators(): List<GenericFunction> {
returns("List<Pair<T, R>>")
body {
"""
return merge(array) { (t1, t2) -> t1 to t2 }
return merge(array) { t1, t2 -> t1 to t2 }
"""
}
}
@@ -273,7 +273,7 @@ fun generators(): List<GenericFunction> {
returns("Sequence<Pair<T, R>>")
body {
"""
return MergingSequence(this, sequence) { (t1, t2) -> t1 to t2 }
return MergingSequence(this, sequence) { t1, t2 -> t1 to t2 }
"""
}
}