Why is `fun <T> something(): T = TODO()` all...
# language-proposals
Why is
fun <T> something(): T = TODO()
allowed, but
val <T> something : T get() = TODO()
is not? I would think the two are equivalent.
Because there is no syntax to specify type arguments for property access If
used in receiver then it's always possible to infer
from it (because all types in receiver should be inferred before call/access itself) But if
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
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.
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!
In functions you can specify the type with angle brackets. A call to
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
and then on the call site hint at the type somehow. E.g.:
Copy code
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
@dmitriy.novozhilov in the future can be possible to do, for example,
if it is a getter? The syntax doesn’t collide with functions as they do
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?
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
@Javier There is no such plans. Just use functions