blitz-foundation / monkey2

zlib License
3 stars 0 forks source link

[language power up] Auto-detecting generic type by left-side value #44

Open Pharmhaus-2 opened 5 years ago

Pharmhaus-2 commented 5 years ago

Original Author: engor

I'm very familiar with Java, and there is a cool feature - auto-detecting generic types by variables types. If compiler knows type of assignable variable then it uses its type as generic type (allow us to omit generic type). It's very nice!

Look at my demo:

Namespace myapp

#Import "<std>"

Using std..

Function Main()

    Local o:Object
    Local v:MyView
    'v=ToView( o )          ' doesn't work, but compiler knows type of 'v'
                        ' and can pass it under the hood as ToView<MyView>
    v=ToView<MyView>( o )' works
End

Class View

End

Class MyView Extends View

End

Function ToView<T>:T( value:Object ) Where T Extends View

    Return Cast<T>( value )
End

With such mechanism we can simplify casting enums to/from integers:

Function ToEnum<T>:T( value:Int )

    Return Cast<T>( value )
End
' usage:
Local e:MyEnum
Local i:=3
e=ToEnum( i ) ' the same as Cast<MyEnum>( i ) but a little clearer.

And core function Cast< T >() also can be simplified with automatically type detection Local e:MyEnum=Cast( 1 ) ' Int to MyEnum

And excuse me for the flight of my dreams. :)