7 ms·
Cool to see Java getting these features. After having been a Java dev most of my life, and then moving to Typescript years ago, it's hard to believe I went so l
by hn_throwaway_99 5y ago
Cool to see Java getting these features. After having been a Java dev most of my life, and then moving to Typescript years ago, it's hard to believe I went so long without this.
Related, Typescript is the only language I know of that through flow analysis does not require you to redefine the variable. E.g. you can do something like
if (typeof foo === 'string') {
//Typescript knows foo is a string here
}
All the other languages I know of, like this proposal for Java, require the variable to be redefined. I personally find the Typescript way, as VSCode will give you appropriate type warnings in the right places, easier to use in practice. Just curious if there are any other languages that do it like TS.
- jung_j 5y agoJava 14 does have something similar https://openjdk.java.net/jeps/305 https://openjdk.java.net/jeps/305
- hn_throwaway_99 5y agoNo, Java requires you to redefine the variable, i.e. if (obj instanceof String s) { // s is a String here, but obj is not }
- Pet_Ant 5y agoThat I would say still counts as “similar” not “the same”
- SemanticStrengh 5y agobut is it a deep copy??
- sebazzz 5y agoIt is not a copy. It still references the same object.
- danachow 5y agoThat’s the same, just that the scoped definition is implicit.
- hn_throwaway_99 5y agoNo, that's the entire point of my question. In Typescript (and Kotlin, as others have noted), the type system knows within the scope of that if statement that obj is a string, so it lets you call string-specific methods on obj withOUT introducing the new variable s.
- danachow 5y agoWhat I'm saying is that this: if (typeof obj === 'string') { // obj is a string } is really not anything meaningfully different than this if (obj is string as obj) { // as in C# // obj is a string (shadowing the outer scoped obj) } or this if (obj instanceof String obj) { // obj is a String here } you can imagine a pseudo TypeScript language like this if (typeof obj === 'string' as obj) { // obj is a string } Actual TypeScript merely allows you to elide the "as obj" and all it needs to trigger this is the "typeof obj === <string literal>" inside of an if expression. This can be done by a simple syntactic replacement, it doesn't require control flow analysis to get this specific feature. But yes, if you have a more general computed expression, that would apply, but that was not the case you were stating. Ie the variable isn't the issue (redefining in this case seems like a distinction without a difference)... However this does work in TS, which is a demonstration of CFA: const isStr = typeof obj === "string"; if (isStr) { // obj is str } For what it's worth I think CFA is useful in TypeScript based on it at its core being a structural typed bandaid over JS, but I think these specific CFA type narrowing features are redundant in stronger typed languages.
- pjmlp 5y agoJava cannot do the same without breaking backwards compatibility, hence the idea to introduce a variable explicitly.
- Smaug123 5y agoF# also has: let foo : obj = failwith "" match foo with | :? SomeType as blah -> // use blah : SomeType (You're allowed to just use the identifier `foo` in the match arm.)
- halfmatthalfcat 5y agoAs does Scala: match thing { case a: String => // use a as string case a @ MyCaseClass(b: String, c, d) => // use a as the instance of MyCaseClass or use b as a string }
- Squarex 5y agoKotlin is the same as typescript.
- swaranga 5y agoThere are some edge cases because of which this had to be done, I think. For example calling static methods via the instance variables, the actual method called would be the static type of the variable at compile time and not the actual type at runtime: public static void main(String[] args) { Parent instance = new Child(); if (instance instanceof Child p) { instance.print(); // prints Parent p.print(); // prints Child } } static class Parent { static void print() { System.out.println("Parent"); } } static class Child extends Parent { static void print() { System.out.println("Child"); } } Hence, with flow typing, existing code could break in subtle ways.
- SemanticStrengh 5y agoHow does Kotlin solve those use cases? > instance.print(); // prints Parent why? the parent print should be shadowed/overidden by the child bruh
- spullara 5y agostatics don't override
- SemanticStrengh 5y agooops my bad
- yarg 5y agoDoes java provide warnings against calling static methods on Objects?
- smarks 5y agoYes, if javac is given the `-Xlint:static` option.
- hilbertseries 5y agoIf you’re writing code calling static methods on instances of classes, you deserve to have that code broken.
- papercrane 5y agoThe Typescript way would only work for local variables in Java. Since another thread might update a field between the instanceof check and the use of the field.
- SemanticStrengh 5y agothose cases are rare. Defensive copying should be optin, not the default. Java really deep copy objects for even the most basic instanceof checks??
- kaba0 5y agoYou can’t change the object’s type in Java, so if you hold on to the same reference it will be safe to use after the instanceof check.
- zarzavat 5y agoYou’re definitely holding it wrong if you have polymorphic fields in your lock-free shared memory. Or at least holding it weirdly.
- gizmo686 5y agoThats the problem with language design. If the language allows something, it needs to correctly support it; even if actually doing it is a bad idea.
- peterkelly 5y agoThis is an issue in TypeScript even with single-threaded code; it (always/sometimes?) assumes function calls won't affect the results of type narrowing tests: https://github.com/microsoft/TypeScript/issues/9998 https://github.com/microsoft/TypeScript/issues/9998
- pkulak 5y agoKotlin does that as well, and it's a JVM language.
- SemanticStrengh 5y agoDon't be mistaken, Typescript do not has proper pattern matching support, The proposal is far from being adopted https://github.com/tc39/proposal-pattern-matching https://github.com/tc39/proposal-pattern-matching > Related, Typescript is the only language I know of that through flow analysis does not require you to redefine the variable. E.g. you can do something like This is called smart casting and is widely used in Kotlin
- viewfromafar 5y agoThe PL crowd calls that type system feature "occurrence typing."
- SemanticStrengh 5y agoyes or flow typing https://en.wikipedia.org/wiki/Flow-sensitive_typing https://en.wikipedia.org/wiki/Flow-sensitive_typing It probably overlap with the research on gradual typing too
- PartiallyTyped 5y agoMypy (Python) does this as well. VSCode and PyCharm provide typehints after if isinstance(foo, str): # code
- dehrmann 5y agoSometimes. If foo isn't local scope, this won't work because it could be modified in another thread.
- cwalv 5y agoI used to find the workaround pretty jarring: lfoo = nonlocal_foo if isinstance(lfoo, ...): Since the checker is correct in these cases, I accepted the ugly and got used to it pretty quickly
- skybrian 5y agoDart also does this.
- markdog12 5y agoAnd it's getting patterns too: https://github.com/dart-lang/language/tree/master/working/0546-patterns https://github.com/dart-lang/language/tree/master/working/05...
- danachow 5y agoThat’s not dataflow analysis. It looks like a cast similar to something like in C# ie: if (foo is string as foo) where the “as foo” scoped variable is implicit. It’s basically implicitly redefining the variable with limited scope. Type guards are a slick feature but it is just an expression match and some syntactic sugar. Even user defined type guards in typescript have to be explicitly declared as such. This would be more an example of CFA. const a = “string”; if (typeof v === a)
- hn_throwaway_99 5y agoIt's not just a simple cast, but I should have used the correct term which is "control flow analysis". It's not just redefining the variable, control flow analysis works in lots of different places besides just typeof checks, and is possible in many cases because TS is structurally typed, not nominally typed.
- TheMatten 5y agoAnd of course, Haskell has equivalent too: case eqT @a @String of Just Refl -> ...
- moomin 5y agoRefinement typing (the TS way) is relatively common in type systems that sit on top of dynamic languages because basically they have no choice. Binding to a new variable, however, is a heck of a lot easier to analyse so tends to be done in languages that don’t need to implement refinement typing. A couple of interesting exceptions: explicit interfaces make it impractical in C#, and there’s a project called liquid Haskell that adds refinement typing on top of an already strong type system.
- dwaite 5y agoSome of this is a consequence of how typescript works - it carries any structural constraints it can find forward in an advisory capacity, because it is somewhat decoupled from the quite-dynamic runtime behavior of the javascript engine. It isn't even block-based scoping in the flow analysis above - if in your block there was the code foo = 1; the typescript engine would then expect that foo will behave like a Number at runtime. I haven't dived in deep enough, but I suspect foo could even have different structural type information within the same expression, e.g. a ternary (typeof foo === 'string') ? something(foo) : somethingelse(foo)
- ygra 5y agoIt's expression-based as well This doesn't only apply to conditional expressions, but also things like typeof foo === 'string' && ...
- saghm 5y agoIn my compilers class, this is how we did static downcasting for the toy language we created (I think it was called Oat?). I think it's clever, but I find that I prefer mechanisms that rebind the variable for clarity purposes. It's super easy IMO to accidentally gloss over something as being just a regular if statement rather than something that's actually statically changing the type of the variable compared to having different syntax than just a regular conditional. I also tend to prefer being able to look at a variable's usage and then look back to the time it was initialized and know that it's still the same type; having the type change only within a given scope without any explicit binding seems like something I'd mess up a lot, especially when reviewing code I didn't write myself.
- arthurcolle 5y ago> All the other languages I know of, like this proposal for Java, require the variable to be redefined. can you give a few examples? This makes no sense to me and I've touched quite a few ecosystems in my time. Maybe I am misunderstanding but my current understanding makes this seem not realistic
- gizmo686 5y agoConsider the following pseudo-Java: Object foo = ... if (foo instanceof String) { System.out.println(foo.toLowerCase()) } The above is not valid Java, because foo has type Object, which does not have a toLowerCase() method, so the compiler refuses to compile it. What you need to do is something like: Object foo = ... if (foo instanceof String) { String sfoo = (String) foo System.out.println(sfoo.toLowerCase()) } Granted, you don't necessarily need to explicitly redefine in, as Java allows anonymous casting: Object foo = ... if (foo instanceof String) { System.out.println(((String) foo).toLowerCase()) } Regardless, the point still stands. Java (and most strongly typed languages with an inheritance based type system) requires an explicit cast, even if a straight forward static analysis would show that the object in question is already the desired type.
- GavinBierman 5y agoThis is all true, but with pattern matching for instanceof you don't need the explicit cast: Object foo = ... if (foo instanceof String s) { System.out.println(s.toLowerCase()) } In this case, the scope of the pattern variable `s` is just the then block, so are free to reuse it elsewhere in the block.