Weird Error

Please take a look at this code

  class A(Name: String) { }

  class B(name: String){   
          fun createA(): A {   
           return A(name)   
          }

  }

Being a Kotlin noob, I thought function createA() would have access to ‘name’; now I know it doesn’t, but that’s not the issue.

Instead of “Unresolved reference: name”, compiler gives this error: “Type mismatch: inferred type is B but java.io.File was expected”. Why is inferred type B? Why is File expected?
When I realised that ‘name’ I am passing to A constructor is not ‘name’ I received in B constructor, I tried to ‘Navigate To’ name, and that took me to Files.kt (in kotlin.io package), line 38: inline val File.name: String

So, how did that happen? :slight_smile:

I want my money back!

I don't have an answer to the question, but it raises a good point anyway. I think createA() should have access to 'name'. I think the (in)visibility rules of Kotlin's constructor parameters are the most surprising part of its syntax. The lexical structure of the code makes it look like 'name' should be in scope. And if you nest a function inside another function the structure is identical and the inner function can see the outer function's parameters. So it's not consistent.

Increasing the visibility of constructor parameters would get rid of the need to prefix them with ‘private val’ if you want to use them in a method.

FWIW, Scala’s syntax is almost identical in this area and constructor parameters are visible in method bodies.

This is an unfortunate bug. Must be fixed in the nightly builds already.