- KICK BAMA KICK
- Mar 2, 2009
-
|
Real dumb question but it's been impossible to Google. Looking at the official tutorials and in this example
code: override def equals(that: Any): Boolean =
that.isInstanceOf[Date] && {
val o = that.asInstanceOf[Date]
o.day == day && o.month == month && o.year == year
}
why are isInstanceOf and asInstanceOf called with square brackets instead of parentheses?
e: oh are those methods generics that actually take no arguments?
KICK BAMA KICK fucked around with this message at 05:31 on Oct 10, 2015
|
#
¿
Oct 10, 2015 05:28
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 10, 2024 06:12
|
|
- KICK BAMA KICK
- Mar 2, 2009
-
|
I think the intentions of this are pretty clear; a case class (more just to convey the intention of immutability and for the free equals and hashCode than for pattern matching) that is only constructed from the companion's parameterless factories.
code:case class Foo private(arg: Seq[Bar]) {/* stuff */}
object Foo {
apply(): Foo = new Foo(someDefaultArgument)
otherFactory(): Foo = new Foo(differentArgument)
}
When I defined apply without the parentheses and tested it in the REPL, val f = Foo() threw an error because it couldn't resolve the ambiguity between the helper's apply method and the class's constructor. This doesn't make any sense to me, since a) if I don't supply an argument, isn't it obvious that I'm calling the one that doesn't take an argument? and b) that constructor is supposed to be private anyway.
So my questions are 1) why? 2) is that how you implement what I'm trying to do? and 3) I guess whatever the convention is on factory methods that take no arguments and otherwise have no side effects, would you define and call otherFactory with parentheses just to match the apply version? I know it doesn't make a difference but it would bug me.
|
#
¿
Oct 27, 2015 05:43
|
|
- KICK BAMA KICK
- Mar 2, 2009
-
|
Didn't have any default arguments and I don't even know what the _* operator does. When I compile:
code:case class Foo private(arg: Seq[Int]) {}
object Foo {
def apply: Foo = new Foo(Seq())
def otherFactory: Foo = new Foo(Seq(0))
}
and then try it at the SBT console I get:
code:scala> val f = Foo()
<console>:10: error: overloaded method value apply with alternatives:
(arg: Seq[Int])Foo <and>
=> Foo
cannot be applied to ()
val f = Foo()
and when I add parentheses to def apply(): Foo = new Foo(Seq()) it works as expected. I get that it synthesizes a companion that doesn't require new but is it also synthesizing a factory with no arguments for this class? No big deal cause as you suggested there's a perfectly appropriate name for the default factory rather than apply but that behavior seemed weird to me.
|
#
¿
Oct 27, 2015 16:37
|
|
- KICK BAMA KICK
- Mar 2, 2009
-
|
Foo() is short for Foo.apply(), but there's no function with that signature. There's a Foo.apply and a Foo.apply(Seq[Int]).
OK, thanks. Got confused by how you can omit the parentheses sometimes.
|
#
¿
Oct 28, 2015 03:42
|
|