failwith in the explicit object constructor using F# - class

The following code
type A (b) =
new () =
if true then A 4.
else failwith ""
gives an error:
This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor.
This works:
type A (b) =
new () =
if true then A 4.
else failwith ""; A 4.
Simple question. What is so bad about failwith in the constructor?

The issue is not failwith per se. As the error indicates, non-primary constructors are restricted. This is to encourage putting all initialization logic in the primary constructor. Your example seems contrived. If you show more of what you're trying to do perhaps someone can offer a solution.
Here's one way to rework your code:
type A (b) =
new () = A(4.0) then
if true then failwith ""
then acts like a do binding in non-primary constructors.
See the MSDN page on Constructors for more options.
EDIT
kvb made a good point regarding primary constructors with side effects. If that's the case you may want to consider moving your logic to a static method. This makes it obvious that other work may be done prior to calling the constructor.
type A (b) =
static member Create() =
if true then failwith ""
else A(4.0)

The problem you are seeing is not specific to failwith; it would also occur with any other expression of type A other than a constructor call, such as Unchecked.defaultof<A>. As the error message indicates, constructors have restrictions on the kinds of expressions that can be used within them to ensure that types are always initialized soundly.
As I mentioned in a comment on Daniel's answer, if you want to fail fast in certain cases you could do something like:
new() =
if true then failwith ""
A 4.0
This will throw an exception before it gets a chance to execute the chained constructor call.

Related

Swift generics: How to represent 'no type'?

I am using Google's promises library, and I would like to create promise without any type (because I don't need any).
However, I am being forced to pick some type:
let promise = Promise<SomeType>.pending()
Is there a type I could pass in place of SomeType that would essentialy mean 'no type', when I need promises just for async flow and exception catching, but I don't want to return a specific value from a function?
For example, some type whose only valid value is nil?
I have encountered this problem in multiple places, the only workaround I found so far is to always provide a non-generic alternative, but it gets really tedious and leads to duplicate code.
Types are sets of values, like Int is the set of all integer numbers, String is the set of all sequences of characters and so on.
If you consider the number of items in the set, there are some special types with 0 items and 1 items exactly, and are useful in special cases like this.
Never is the type with no values in it. No instance of a Never type can be constructed because there are no values that it can be (just like an enum with no cases). That is useful to mark situations, code flow etc as 'can't happen', for example the compiler can know that a function that returns Never, can never return. Or that a function that takes Never can never be called. A function that returns Result<Int, Never> will never fail, but is in the world of functions returning Result types. But because never can't be constructed it isn't what you want here. It would mean a Promise that can't be fulfilled.
Void is the type with exactly 1 value. It's normally spelled () on the left and Void on the right, of a function definition. The value of a void is not interesting. It's useful to make a function that returns Void because those are like what other languages call subroutines or procedures. In this case it means a Promise that can be fulfilled but not with any value. It can only be useful for its side effects, therefore.
Is it a correct solution or a workaround if we create an empty class
class Default_Class : Codable {
}
and use this as Promise<Default_Class>.pending

Why direct usage of generic value is not possible but same is possible if returned from method in Dart

Why is it assigning a value to a generic field is not possible when assigned directly, but same is possible when using a variable reference or method return value (here, same value is assigned to the variable and method returns the same value)?
class User {}
class Teacher extends User {}
class Student extends User {}
Future<User> getUser() {
return Future.value(Student());
}
void main() {
Future<Future<User>> fut = Future.value(getUser()); // <----- No error
Future<Future<User>> fut2 = Future.value(Future.value(Student())); // <----- Getting error
Future<User> userFut3 = Future.value(Student());
Future<Future<User>> fut3 = Future.value(userFut3); // <----- No error
}
Getting below error when Future.value(Future.value(Student())) assigned directly.
Error: The argument type 'Student' can't be assigned to the parameter type 'FutureOr<Future<User>>?'.
The issue here is that the parameter of Future<T>.value has the type FutureOr<T>. It can be either a future or a value.
Also, Dart type inference works by "pushing down" a context type, then trying to make the expression work at that type, and finally pushing the final static type back up.
If an expression like Future.value(...) has a context type, the missing type argument is always inferred from the context type.
When you write
Future<Future<User>> fut2 = Future.value(Future.value(Student()));
the context type of the outer Future.value, the type we know it should have, is Future<Future<User>>. That makes its argument have context type FutureOr<Future<User>>.
The argument is Future.value(Student()), where we don't yet know anything about Student() because we haven't gotten to it in the type inference yet, we're still working out way down towards it.
A Future<X> can satisfy that FutureOr<Future<User>> in two ways, either by being a Future<User> or by being a Future<Future<User>>.
Type inference then guesses that it's the latter. It's wrong, but it can't see that yet. The way type inference works, it has to use the context type when there is one, but the context type is ambiguous, and it ends up choosing the wrong option.
You are hitting an edge case of the type inference where the context type can be satisfied in two different ways, and the downwards type inference chooses the wrong one. It's a good heuristic that if you have a FutureOr<...> context type, and you see a Future constructor, you want the Future-part of the FutureOr<...>. It breaks down when you have FutureOr<Future<...>>. So, don't do that!
My recommendation, in complete generality, is to never have a Future<Future<anything>> in your program. Not only does it avoid problems like this, but it's also a better model for your code.
A future which eventually completes to something which eventually completes to a value ... just make it eventually complete to that value directly. Waiting for the intermediate future is just needless busywork.
Because in the function you defined the return type and dart knows the return type, but when assigning directly dart does not know Future.value(Student()) has a type of Future<User>. to fix this you have to tell the dart the type of the value, like this: Future.value((Future.value(Student())) as Future<User>);
this way dart will know the type of this value and treat it as a Future<User>.

Better way to call a private method

I'm using CoffeeScript to create a class and build a private method, but my code feels kludgy.
As in the example below, first I define the method with = and then I am forced to use the call method on the portion to be used. But this seems like a kludgy workaround, so I want to know if there is a cleaner solution.
class Human
constructor: (#name, #height, #weight) ->
_realWeight = ->
#weight
answerWeight: ->
console.log(_realWeight.call(#) - 5)
$ ->
ken = new Human('Ken', 165, 70)
ken.answerWeight()
TL;DR
No.
Longer Answer
There is only one way to have truly private data in javascript/coffeescript: closures.
First, lets consider some alternatives:
Symbols
Because symbols are unique they can be used to create psuedo-private data:
you can only access the property if you have a reference to the symbol its keyed to:
foo = Symbol('I am unique')
bar = {}
bar[foo] = "I am almost private"
Code that doesn't have access to foo can't easily get to that property of bar except for Object.getOwnPropertySymbols. So not easy to break, but breakable.
Underscores
Typical naming convention says that properties/methods prefixed or followed by an underscore are 'private', they are not to be used by an external caller. However, that 'privacy' is not in any way enforced by the runtime.
So lets talk about closures.
Simple Closure example
makeFoo = (something) -> getSomething: -> something
foo = makeFoo(3)
foo.something # undefined
foo.getSomething() # 3
Now there is no way to get at the parameter passed to the constructor except to call the method. This pattern, while slightly more elegant in coffeescript, is still kinda lame. Lots of duplicated function objects. Not so bad for just getSomething, but add a bunch of methods and it gets ugly fast. Also, typically not as easily optimized by the JIT compiler as foo = new Foo() would be. Fortunately, ES 2015 to the rescue:
Advanced Closure Example
Foo = null
do ->
privateData = new WeakMap()
getSomething = -> privateData.get(this)
Foo = class Foo
constructor: (something) -> privateData.set(this, something)
getSomething: getSomething
foo = new Foo(3)
foo.something # undefined
foo.getSomething() # 3
new Foo(42).getSomething() # 42
foo instanceof Foo # true
Now all instances of Foo share one copy of getSomething rather than each getting their own. The weakmap is hidden in the closure created by the IIFE, and because of the 'weak' part of WeakMap when the instance gets garbage collected the private data will be as well. You are also now potentially able to enjoy the benefits of the compiler optimizing newly created objects. Last but not least, instanceof still works properly (to the extent that it ever works properly).
Further reading.
Even More reading
Note
WeakMaps are not supported in all browsers (for IE its 11 or bust). There is a shim, but it cannot be completely polyfilled. Whether or not the shim gets close enough is a call you'll have to make.

Scala instance value scoping

Note that this question and similar ones have been asked before, such as in Forward References - why does this code compile?, but I found the answers to still leave some questions open, so I'm having another go at this issue.
Within methods and functions, the effect of the val keyword appears to be lexical, i.e.
def foo {
println(bar)
val bar = 42
}
yielding
error: forward reference extends over definition of value bar
However, within classes, the scoping rules of val seem to change:
object Foo {
def foo = bar
println(bar)
val bar = 42
}
Not only does this compile, but also the println in the constructor will yield 0 as its output, while calling foo after the instance is fully constructed will result in the expected value 42.
So it appears to be possible for methods to forward-reference instance values, which will, eventually, be initialised before the method can be called (unless, of course, you're calling it from the constructor), and for statements within the constructor to forward-reference values in the same way, accessing them before they've been initialised, resulting in a silly arbitrary value.
From this, a couple of questions arise:
Why does val use its lexical compile-time effect within constructors?
Given that a constructor is really just a method, this seems rather inconsistent to entirely drop val's compile-time effect, giving it its usual run-time effect only.
Why does val, effectively, lose its effect of declaring an immutable value?
Accessing the value at different times may result in different results. To me, it very much seems like a compiler implementation detail leaking out.
What might legitimate usecases for this look like?
I'm having a hard time coming up with an example that absolutely requires the current semantics of val within constructors and wouldn't easily be implementable with a proper, lexical val, possibly in combination with lazy.
How would one work around this behaviour of val, getting back all the guarantees one is used to from using it within other methods?
One could, presumably, declare all instance vals to be lazy in order to get back to a val being immutable and yielding the same result no matter how they are accessed and to make the compile-time effect as observed within regular methods less relevant, but that seems like quite an awful hack to me for this sort of thing.
Given that this behaviour unlikely to ever change within the actual language, would a compiler plugin be the right place to fix this issue, or is it possible to implement a val-alike keyword with, for someone who just spent an hour debugging an issue caused by this oddity, more sensible semantics within the language?
Only a partial answer:
Given that a constructor is really just a method ...
It isn't.
It doesn't return a result and doesn't declare a return type (or doesn't have a name)
It can't be called again for an object of said class like "foo".new ("bar")
You can't hide it from an derived class
You have to call them with 'new'
Their name is fixed by the name of the class
Ctors look a little like methods from the syntax, they take parameters and have a body, but that's about all.
Why does val, effectively, lose its effect of declaring an immutable value?
It doesn't. You have to take an elementary type which can't be null to get this illusion - with Objects, it looks different:
object Foo {
def foo = bar
println (bar.mkString)
val bar = List(42)
}
// Exiting paste mode, now interpreting.
defined module Foo
scala> val foo=Foo
java.lang.NullPointerException
You can't change a val 2 times, you can't give it a different value than null or 0, you can't change it back, and a different value is only possible for the elementary types. So that's far away from being a variable - it's a - maybe uninitialized - final value.
What might legitimate usecases for this look like?
I guess working in the REPL with interactive feedback. You execute code without an explicit wrapping object or class. To get this instant feedback, it can't be waited until the (implicit) object gets its closing }. Therefore the class/object isn't read in a two-pass fashion where firstly all declarations and initialisations are performed.
How would one work around this behaviour of val, getting back all the guarantees one is used to from using it within other methods?
Don't read attributes in the Ctor, like you don't read attributes in Java, which might get overwritten in subclasses.
update
Similar problems can occur in Java. A direct access to an uninitialized, final attribute is prevented by the compiler, but if you call it via another method:
public class FinalCheck
{
final int foo;
public FinalCheck ()
{
// does not compile:
// variable foo might not have been initialized
// System.out.println (foo);
// Does compile -
bar ();
foo = 42;
System.out.println (foo);
}
public void bar () {
System.out.println (foo);
}
public static void main (String args[])
{
new FinalCheck ();
}
}
... you see two values for foo.
0
42
I don't want to excuse this behaviour, and I agree, that it would be nice, if the compiler could warn consequently - in Java and Scala.
So it appears to be possible for methods to forward-reference instance
values, which will, eventually, be initialised before the method can
be called (unless, of course, you're calling it from the constructor),
and for statements within the constructor to forward-reference values
in the same way, accessing them before they've been initialised,
resulting in a silly arbitrary value.
A constructor is a constructor. You are constructing the object. All of its fields are initialized by JVM (basically, zeroed), and then the constructor fills in whatever fields needs filling in.
Why does val use its lexical compile-time effect within constructors?
Given that a constructor is really just a method, this seems rather
inconsistent to entirely drop val's compile-time effect, giving it its
usual run-time effect only.
I have no idea what you are saying or asking here, but a constructor is not a method.
Why does val, effectively, lose its effect of declaring an immutable value?
Accessing the value at different times may result in different
results. To me, it very much seems like a compiler implementation
detail leaking out.
It doesn't. If you try to modify bar from the constructor, you'll see it is not possible. Accessing the value at different times in the constructor may result in different results, of course.
You are constructing the object: it starts not constructed, and ends constructed. For it not to change it would have to start out with its final value, but how can it do that without someone assigning that value?
Guess who does that? The constructor.
What might legitimate usecases for this look like?
I'm having a hard time coming up with an example that absolutely
requires the current semantics of val within constructors and wouldn't
easily be implementable with a proper, lexical val, possibly in
combination with lazy.
There's no use case for accessing the val before its value has been filled in. It's just impossible to find out whether it has been initialized or not. For example:
class Foo {
println(bar)
val bar = 10
}
Do you think the compiler can guarantee it has not been initialized? Well, then open the REPL, put in the above class, and then this:
class Bar extends { override val bar = 42 } with Foo
new Bar
And see that bar was initialized when printed.
How would one work around this behaviour of val, getting back all the
guarantees one is used to from using it within other methods?
Declare your vals before using them. But note that constuctor is not a method. When you do:
println(bar)
inside a constructor, you are writing:
println(this.bar)
And this, the object of the class you are writing a constructor for, has a bar getter, so it is called.
When you do the same thing on a method where bar is a definition, there's no this with a bar getter.

scala: why does underscore (_) initialization work for fields but not method variables?

this works:
scala> class foo[T] {
| var t: T = _
| }
defined class foo
but this doesn't:
scala> def foo[T] = {
| var t: T = _
| }
<console>:5: error: local variables must be initialized
var t: T = _
why?
(one can use:
var t: T = null.asInstanceOf[T]
)
There is a mailing list thread where Martin answered:
It corresponds to the JVM. You can omit a field initialization but not a local variable initialization. Omitting local variable initializations means that the compiler has to be able to synthesize a default value for every type. That's not so easy in the face of type parameters, specialization, and so on.
When pressed about how there is or should be any distinction between fields and locals in the matter of Scala synthesizing default values, he went on to say:
In terms of bytecodes there IS a clear difference. The JVM will initialize object fields by default and require that local variables are initialized explicitly. […] I am not sure whether we should break a useful principle of Java (locals have to be initialized before being used), or whether we should rather go the full length and introduce flow-based initialization checking as in Java. That would be the better solution, IMO, but would require significant work in terms of spec and implementation. Faced with these choices my natural instinct is to do nothing for now :-)
So if I understand correctly, the Scala compiler does not actually synthesize default values for object fields, it produces bytecode that leaves the JVM to handle this.
According to SI-4437 there was agreement from Martin on actually endorsing the null.asInstanceOf[T] pattern in the language spec, seemingly for lack of being able to feasibly support a better alternative within existing constraints.
This is defined in section 4.2 of the Scala Language Specification (my italics)
A variable definition var x: T = _ can appear only as a member of a template. It
introduces a mutable field with type T and a default initial value
This, of course, does not answer the why this should be so!
Here is at least one use case that I just uncovered. When then superclass initializes member variables via reflection it can actually initialize a subclasses member variables. However, if a subclass also initializes the member variable with a value, then this will have the effect of overwriting the value that the superclass gave it. This can be avoided by initializing the subclasses member variable with the underscore. This is why the language spec talks about giving the variable a getter function that returns the current value a little further down from the quoted sentence in oxbow_lake's sentence.