Why is `fun <T> something(): T = TODO()` all...
# language-proposals
n
Why is
fun <T> something(): T = TODO()
allowed, but
val <T> something : T get() = TODO()
is not? I would think the two are equivalent.
d
Because there is no syntax to specify type arguments for property access If
T
used in receiver then it's always possible to infer
T
from it (because all types in receiver should be inferred before call/access itself) But if
T
is used only in return type then there will be cases when compiler can not infer it, like
Copy code
val x = something // no information to infer T
y
Btw you can technically suppress that error, but you run into a lot of other code-breaking bugs whenever T can't be figured out from the context. It's just not worth it to suppress it at all.
d
I don’t think I understand why functions are different here though? Oh, and hi @Youssef Shoaib [MOD] - good to see you here as well as commenting on my YouTube channel!
y
In functions you can specify the type with angle brackets. A call to
funSomething
would simply tell you to specify a type arg. There's obviously the simple fix of just specifying the type on call site, but in some places that gets messy. Here's a hack though. You can
@Suppress(TYPE_PARAMETER_OF_PROPERTY_NOT_USED_IN_RECEIVER")
and then on the call site hint at the type somehow. E.g.:
Copy code
@Suppress("TYPE_PARAMETER_OF_PROPERTY_NOT_USED_IN_RECEIVER")
val <T> something: T get() = TODO()
fun <T> coerce(x: T): T = x
fun main() {
    //val x = something //Error
    val x2: Int = something 
    val x3 = coerce<String>(something)
    coerce<Boolean>(something) //even works as an unused expression!
    println("Hello, world!!!")
}
Good to see you too Duncan! I've been enjoying the videos as per usual! Keep it up
👯‍♂️ 1
j
@dmitriy.novozhilov in the future can be possible to do, for example,
property<T>
if it is a getter? The syntax doesn’t collide with functions as they do
foo<T>()
d
Ah I see, it’s about the call-site syntax. So because we don’t have this ^ the type only makes sense as a receiver. Maybe Type parameter of a property can only be used as its receiver type would be a better message?
y
Maybe Type parameter of a property can only be used as its receiver type would be a better message?
Using it as part of the receiver type is valid too. E.g.:
Copy code
val <T> List<T>.first: T
💡 1
d
@Javier There is no such plans. Just use functions