Initialize a triangle mesh

Skip to first unread message

Maia R.

Jan 12, 2021, 2:47:45 PMJan 12
to scalismo
I have a question, both for Scala and Scalismo.

I have created a case class that needs a field of TriangleMesh type. As far as I know, class fields need to be initialized in Scala. How would you initialize a mesh as below ?
case class myClass(data: String) {

var referenceMesh: TriangleMesh[_3D] = ???

def setReferenceMesh(mesh: TriangleMesh[_3D]): Unit =  {
referenceMesh  = mesh

// other methods which use referenecMesh
def method1(): Unit = {
// use referenceMesh field here   


Thank you
Best regards

Marcel Luethi

Jan 13, 2021, 6:02:16 AMJan 13
to Maia R., scalismo
Hi Maia

The ideal solution would be to pass the reference mesh in the constructor. This has the advantage, that the variable is never uninitialized and the object is always in a valid state. This would allow you do use a val instead of a var, which is preferred in Scala.

While it is possible to use setter methods in Scala, it is usually discouraged.  If you really have to use this approach, you can either initialize it with null or, preferably, use instead a variable of type Option[Triangle], which you initially set to None and then reset it to Some(mesh). This will avoid these nasty nullpointer exceptions and safe you a lot of trouble later. But as said, the best option is not to use var in the first place.

Best regards,


You received this message because you are subscribed to the Google Groups "scalismo" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

Andreas Morel-Forster

Jan 13, 2021, 6:09:10 AMJan 13

A bit out of sync as I accidently replied privately earlier on instead on this list :-/


Without knowing your application you havI think it would be better Scala if you would use a case class including the referenceMesh as a field as data:

case class MyClass(data: String, reference: TriangleMesh[_3D])

val instance: MyClass = ???
val newInstance = instance.copy(reference = newReference)

To create a dummy mesh without anything you can use the following code:

var mesh = TriangleMesh3D(IndexedSeq[Point3D](), TriangleList(IndexedSeq[TriangleCell]()))

Best, Andreas


Jan 13, 2021, 8:05:44 AMJan 13
to Andreas Morel-Forster, Marcel Luethi, scalismo
Thank you very much for all. I include  referenceMesh in my case class as Andreas has suggested and everything is working very well.
Best regards,


Jan 13, 2021, 8:11:45 AMJan 13
to Marcel Luethi, scalismo
Hi Marcel,
Thank you very much for the suggestion and explanation. I followed your advice and everything is working very well (sorry I didn't mention your solution earlier, I saw your message after Andreas's one).
Best regards,
Reply all
Reply to author
0 new messages