Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin unexpected `unresolved reference`

I'm a beginner to Kotlin, and here's my code:

class C(val boy: Int = 0) {
    fun <T, E> boy(i: Int) = i
}

fun girl(b1: Boolean, b2: Boolean) = println("boy($b1, $b2)")

fun main(args: Array<String>): Unit {
    val A = 234 // see? A defined!
    val B = 345 // see? B defined!
    val c = C(123) // c is also defined!

    girl(c.boy < A, B > A) // hey look at here
}

IntelliJ IDEA gives me:

  • unresolved reference: A
  • unresolved reference: B
  • unresolved reference: c

At the line hey look at here.

I think my code is syntactically correct, what's wrong?

like image 575
ice1000 Avatar asked Jun 04 '17 13:06

ice1000


2 Answers

You stumped on a very rare case of syntactic ambiguity. I think it is a first for SO, congrats!

Your initial syntax is technically correct, but in this contexts it also can be interpreted as an attempt to call c.boy<A,B>. Since the compiler didn't know what you meant, it assumed you wanted the function call.

The easiest fix is adding parenthesis as you did or rearranging the expressions:

girl(c.boy < A, A < B)

P.S. Same thing can happen in C#, so it is not unique to Kotlin

like image 60
voddan Avatar answered Nov 02 '22 08:11

voddan


Well.. I solved these errors by adding a pair of braces:

fun main(args: Array<String>): Unit {
    val A = 234
    val B = 345
    val c = C(123)

    girl((c.boy < A), B > A) // hey look at here
}

But I still wonder why my code above doesn't work

Edit: see the other answer

like image 44
ice1000 Avatar answered Nov 02 '22 07:11

ice1000