Logo

Programming-Idioms

Print the value of object x having custom type T, for log or debug.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#include <iostream>
std::cout << x;
print(x);
import fmt;
fmt.Println(x)
print x
console.log(x);
import static java.lang.System.out;
out.println(x);
import static java.lang.System.identityHashCode;
import static java.lang.System.out;
record X<T>(T t) {
    @Override
    public String toString() {
        String s = t.getClass().getName();
        s = "%s<%s>".formatted(getClass().getName(), s);
        return "%s@%x".formatted(s, identityHashCode(this));
    }
}
X<?> x = new X<>(123);
out.println(x);
writeln(x.T);
use Object::Pad;
class Point {
    has $x :param = 0;
    has $y :param = 0;
    
    use overload '""' => sub { shift->_stringify() };   

    method _stringify () { "A point at ($x, $y)"  }
}
 
my $p = Point->new(x => 5, y => 10);

print $p; # prints: A point at (5, 10)
package Point { 
    my $_data = {};
    
    sub new { 
        my $class = shift;
        $_data = { @_ };
        bless $_data, $class;
    };

    use overload '""' => sub { shift->_stringify() };

    sub _stringify {
        my $self = shift;
        return sprintf 'A point at (%d, %d)', $self->{x}, $self->{y};
    }
}
 
my $p = Point->new(x => 5, y => 10);
print $p;
print(x)
puts x
println!("{:?}", x);
Debug.Print x